weixin_33724659 2018-05-12 13:43 采纳率: 0%
浏览 179

使用AJAX更改按钮

I have created a system where you can visit a place and have all the code that allows for an entry to be posted to the database and deleted from the database on button click with ajax but i am struggling to work out how to make the button change with ajax when its clicked depending on whether the record exists or not. At the moment the button only changes if the page is refreshed albeit the AJAX code works for adding or deleting from the database. How would i get my buttons to change and respond to the if statement with AJAX? here is what i have so far:

Html:

@if(Auth::user()->visitors()->where('place_id', $place->id)->first())
      <a class="btn btn-visited visit"  data-id="{{ $place->id }}">I've Visited <i class="fas fa-check"></i></a>
       @else
      <a class="btn btn-not-visited visit"  data-id="{{ $place->id }}">Visited?</a>
@endif

AJAX JS:

var token = '{{ Session::token() }}';
var urlVisit = '{{ route('visitss') }}';

$('.visit').on('click', function (event) {
    event.preventDefault();
    $.ajax({
        method: 'POST',
        url: urlVisit,
        data: {
            place_id: $(event.target).data("id"),
            _token: token
        }
    }).done(function() {
        //
    });
});

php:

$place_id = $request['place_id'];
        $place = place::find($place_id);
        $visited = Auth::user()->visitors()->where('place_id', $place_id)->first();

    if($visited == null) {
                $visited = new Visit();
                $visited->user_id = Auth::user();
                $visited->place_id = $place->id;
                $visited->save();
                return null;
            }
        else{

          $visited->delete();
             return null;
        }

How do i get the buttons to respond with AJAX?

  • 写回答

2条回答 默认 最新

  • weixin_33713350 2018-05-12 14:13
    关注

    You want to change the button on success from Ajax.

    So Insert whatever you want to do in your success function

    $('.visit').on('click', function (event) {
        event.preventDefault();
        $.ajax({
            method: 'POST',
            url: urlVisit,
            data: {
                place_id: $(event.target).data("id"),
                _token: token
            }
        }).done(function() {
            // add button change here
            // select the buttons I'd and manipulate e.g.
           $('#buttonID').html('change');
       });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?