Laravel AJAX show/hide button on response

Belisario Peró :

I have created an AJAX request on button click event which updates a model field to true or false in order to mark model record as liked or disliked.

Context:

  • When user access the view, it must show one or other button depending if the record has the mark of liked or unliked.
  • When user access the view, he will have multiple records and he can like or unlike any of them, so it's needed to post AJAX request and show/hide the correct button in the corresponing HTML element for that model record.

  • HTML Code (this is just one record instance, actual view can have multiple instances of this code based on model records amount)

<div class="kt-portlet__head-toolbar">
    <a href="#" class="btn btn-icon" data-toggle="dropdown" onClick="likeProperty({{$match->matchid}})">
        {{$match->matchid}}
        @if ($match->prop_like == true)
        <i class="flaticon2-bell kt-font-brand likeprop" id="likeprop" name="likeprop"></i>
        @endif
        @if ($match->prop_like == false)
        <i class="flaticon2-bell-4 kt-font-brand unlikeprop" id="unlikeprop" name="unlikeprop"></i>
        @endif
    </a>
</div>
  • Javascript Code
function likeProperty(matchid) {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        method: 'post',
        url: '/processes/offerdemand/matchlike/'+ matchid,
        data: {
            'id': matchid,
        },
        success: function () {
            // hide like button
            $('#likeprop').hide();
            // show like button
            $('#unlikeprop').show();
        },
        error: function (XMLHttpRequest) {
            // handle error
        }
    });
}

Does anyone has idea on this type of requirement?

Regards

James Clark Developer :

If I'm understanding correctly, the problem you have is that the html ids likeprop and unlikeprop are not unique.

The quickest solution to this problem would be to append the record id onto the id so that they are unique. e.g.

<i class="flaticon2-bell-4 kt-font-brand unlikeprop" id="unlikeprop-{{ $match->id }}" name="unlikeprop-{{ $match->id }}"></i>

and

$('#unlikeprop-'+matchid).show();

Juggling ids like this is effective, but can get messy and leads to easy bugs. More modern javascript frameworks such as angular, react, and vue.js try to solve some of these problems by introducing concepts such as two-way data binding. In the long run, you might consider looking into vue.js https://laravel.com/docs/7.x/frontend#writing-vue-components.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31676&siteId=1