I’m trying to build asynchronous follow mechanic using ajax and Laravel. I have two button id’s; follow-up, unfollow. And also there is back-end in blade whether profile is being follow by auth user. If auth user is following the user unfollow button shows up and vice versa. And i also changed id of current button to opposite of it(for follow-up unfollow form unfollow follow-up). But everytime i follow user and try to unfollow it it gives me POST http://localhost:8000/unfollow 404 (Not Found)
and error occurs vice versa. Here is my code samples:
Blade
@auth
@if(auth()->user()->username != $user->username)
<div class="author-btn">
@if(auth()->user()->getFollowing()->where('following_id', $user->id)->first())
<button data-target="{{ $user->username }}" id="unfollow" class="btn btn--md btn--round">
Takipten çık
</button>
@else
<button data-target="{{ $user->username }}" id="follow-up" class="btn btn--md btn--round">
Takip et
</button>
@endif
</div>
<!-- end /.author-btn -->
@endif
@endauth
Javascript
$(document).ready(function() {
$('#follow-up').on('click', function(e){
e.preventDefault();
var t = $('#follow-up');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: '{{ route("follow_up") }}',
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {target:t.attr('data-target')},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
t.html('Takipten çık');
t.attr('id', 'unfollow');
alert(data.msg);
},
error:function(){
alert("İşlem sırasında bir hata oluştu.");
},
});
});
$('#unfollow').on('click', function(e){
e.preventDefault();
var t = $('#unfollow');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: '{{ route("un_follow") }}',
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {target:t.attr('data-target')},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
t.html('Takip et');
t.attr('id', 'follow-up');
alert(data.msg);
},
error:function(){
alert("İşlem sırasında bir hata oluştu.");
},
});
});
});
Source: Laravel