I am trying to add ajax functionality to a like button.
Everything works, except that I get redirected to a page with json data after I click the like button.
I am using e.preventDefault() and it's still redirecting me.
If I use on('click') I get a TokenMismatch error in the console log even though I have included a hidden input with a token.
jquery.min.js:4 POST http://localhost/socialnet/public/likeStatus 500 (Internal Server Error)
If I use on('submit') the data goes through but I get redirected to the page with the json response.
This is in my controller FeedController@likeStatus()
public function likeStatus() {
if (Input::has('like_status')) {
$status = Input::get('like_status');
$selectedStatus = Status::find($status);
$selectedStatus->likes()->create([
'user_id' => Auth::user()->id,
'status_id' => $status
]);
$response = array(
'status' => 'success',
'msg' => 'You have liked this status',
);
return Response::json($response);
}
}
The view
{!! Form::open(['action' => 'FeedController@likeStatus', 'id' => 'like_form']) !!}
{!! Form::hidden('like_status', $status->id) !!}
{!! Form::hidden('user_id', Auth::user()->id) !!}
<button type="submit" name="likeStatus" class="btn btn-info btn-xs" id="like-status">
<i class="fa fa-thumbs-up"></i> Like ()
</button>
{!! Form::close() !!}
The Javascript
$('#like-status').on('click', function(e){
e.preventDefault();
var status_id = $('input[name=like_status]').val();
var user_id = $('input[name=user_id]').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').val()
}
});
$.ajax({
url: 'http://localhost/socialnet/public/likeStatus',
method: 'post',
data: {status_id: status_id, user_id: user_id},
success: function( data ) {
console.log(data.msg);
}
});
});
What am I doing wrong?
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2aiS3SA
via IFTTT
Aucun commentaire:
Enregistrer un commentaire