Belisario Peró
Belisario Peró

Reputation: 637

Laravel AJAX show/hide button on response

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:

<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>
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

Upvotes: 2

Views: 1544

Answers (1)

James Clark
James Clark

Reputation: 1325

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.

Upvotes: 2

Related Questions