Ajax jQuery bring data from database without refresh

Viewed 167

I'm working on a like/dislike system. For that, I don't want to refresh the page to do the like, so I am executing a non-refresh PHP script, it uses jQuery and a form for it:

<form action="<?php echo ROUTE; ?>/dislike.php" id="dislike-form" method="POST">
  <button id="dislike-submit">
    <i id="dislike" class="fa fa-thumbs-o-down" aria-hidden="true"></i>
  </button>
</form>

As you can see, its action is dislike.php. On that file, this code is done:

$sentence = $connection->prepare("
  UPDATE test_likes SET dislikes = dislikes + 1
");
$sentence->execute();

In this case, we would be redirected to dislike.php, but to stop redirecting and to execute the SQL query without reloading the page, I added this on the same file with the form above:

<script>
$('#dislike-form').submit(function(){
  return false;
});

$('#dislike-submit').click(function(){
  $.post( 
    $('#dislike-form').attr('action'),
    $('#dislike-form :input').serializeArray(),
  );
});
</script>

So once the query is executed, it does update the database, but I want to bring the result with jQuery or AJAX once it is done. How can I do this?

1 Answers

You can get the results in either of the following method based on whether its successful or failed. You can find more details here.

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
$.post( "example.php", function() {
  alert( "success" );
})
  .done(function( data ) {
   alert( "Data Loaded: " + data );
  });
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });
 
Related