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

使用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');
       });
    });
    
    评论

报告相同问题?