rafitio rafitio - 23 days ago 6
jQuery Question

jQuery automatically updated value on view when button clicked

i was create like button with current value on database, and when the button has clicked the value must be automatically updated on the view.
currently, the value was successfully updated on database, but not automatically updated on view.

here my jquery code

<script type="text/javascript">
$(document).ready(function(){
$('#like').on('click', function(e){
var id = '{{$news->id}}';
$.get('{{ url('view/like')}}/'+id, function(data){
console.log(id);
console.log(data);
$('#like_data').empty();
$.each(data, function(index, element){
$('#like_data').append("<p>"+this.like+"</p>");
});
});
});
});
</script>


here my controller

public function like($id){

$news = News::find($id);

$news->like += 1;
$news->save();

return $news;
}

Answer

You need to pass JSON response from your controller. Like this

public function like($id){

    $news = News::find($id);

    $news->like += 1;
    $news->save();

    return response()->json([$news], 200);
}

you don't need to use $.each() for this response because you send only single object response. Just simply write this code:

$('#like_data').html("<p>"+data.like+"</p>");

if you want to use each just simply write:

 $.each(data, function (index, element) {
      $("#like_data").append("<p>" + element.like + "</p>");
 }); 
Comments