3

Objective: Query SQL without refreshing the page using Ajax.

I have Like/Dislike buttons that function perfectly as a form and submit input, however, the form refreshes the page.

I have no clue how to make an Ajax call that connects my 'liker.php' (below) to operate within my main page via a class/id div click or button.

$.ajax({
  type: "POST",
  url: "liker.php",
  data: ???
  success: ???
  ...............

I've read some tutorials and looked for answers, but I'm still stumped.

liker.php:

//LIKE FIELD
if (isset($_POST['like'.$id])) {
  if (!in_array("$id", $like_explode)) {
    if (!in_array("$id", $dislike_explode)) {
      mysqli_query($db, "UPDATE likes SET pid_like=CONCAT(pid_like,',$id') WHERE user_id='$user_id'");
      mysqli_query($db, "UPDATE comments SET likes=(likes+1) WHERE id='$id'");
    }
    else
    {
      $new_dislike_string = str_replace(",$id", '', $dislike_string);
      mysqli_query($db, "UPDATE likes SET pid_dislike='$new_dislike_string' WHERE user_id='$user_id'");
      mysqli_query($db, "UPDATE likes SET pid_like=CONCAT(pid_like,',$id') WHERE user_id='$user_id'");
      mysqli_query($db, "UPDATE comments SET likes=(likes+1) WHERE id='$id'");
      mysqli_query($db, "UPDATE comments SET dislikes=(dislikes-1) WHERE id='$id'");
    }
  }
}
//DISLIKE FIELD
if (isset($_POST['dislike'.$id])) {
  if (!in_array("$id", $dislike_explode)) {
    if (!in_array("$id", $like_explode)) {
      mysqli_query($db, "UPDATE likes SET pid_dislike=CONCAT(pid_dislike,',$id') WHERE user_id='$user_id'");
      mysqli_query($db, "UPDATE comments SET likes=(dislikes+1) WHERE id='$id'");
    }
    else
    {
      $new_like_string = str_replace(",$id", '', $like_string);
      mysqli_query($db, "UPDATE likes SET pid_like='$new_like_string' WHERE user_id='$user_id'");
      mysqli_query($db, "UPDATE likes SET pid_dislike=CONCAT(pid_dislike,',$id') WHERE user_id='$user_id'");
      mysqli_query($db, "UPDATE comments SET dislikes=(dislikes+1) WHERE id='$id'");
      mysqli_query($db, "UPDATE comments SET likes=(likes-1) WHERE id='$id'");
    }
  }
}
//LIKE-DISLIKE FIELD END
6
  • post html snippet pleaseeee Commented Jul 27, 2015 at 6:03
  • I'm sure you can find many examples through Google, it isn't that hard. The data would be the identifier i.e if it is a like or a dislike. That can be done however you want. Using bool, ints or even a string. The success callback would be where you would simply update the amount of likes/dislikes. Commented Jul 27, 2015 at 6:08
  • Since I'm not sure how to use Ajax, I just communicate with the php like this: <form action='' method='post'><input type='submit' name='like$id' value='Like' /></form> :( Commented Jul 27, 2015 at 6:08
  • Thanks Script, I'll keep looking. Could you give me an example of how to write the "data" "success" part with my php file? Commented Jul 27, 2015 at 6:09
  • I'm sure someone will write an example. I'm on mobile right now so it would be quite difficult. Commented Jul 27, 2015 at 6:20

3 Answers 3

3

i'll explain you how to use ajax with jquery. I don't understand all how it works $_POST variables, but i'll hope help you.

First use a class to know when a element like/dislike is clicked. Second use a name to know if is a Like or Dislike.

Example for like:

<a href="ID" class="classForLikeOrDislike" name="like">Like</span>

Dislike:

<a href="ID" class="classForLikeOrDislike" name="dislike">Dislike</span>

El ajax

$(".classForLikeOrDislike").click(function(){

    // Get the varible ID, to send to your php
    var id = $(this).attr('href');

    // Get the varible name, to send like or dislike
    var l = $(this).attr('name');


    $.post({url: "liker.php", {id: id}, success: function(result){
        // do some code here
        // here yo can see 'result' response of liker.php
        // console.log(result);
    }});

});

*Update change span tag by anchor tag with href .

UPDATE to response the 'ONLY CLICK' question above

The event variable is something that must be passed to your your anonymous function.

<script>
function chk(event) 
{
    // Prevent trigger submit and reload page
    event.preventDefault();
    var name=document.getElementById('clicker'); 
    $.ajax({
          type:"post",
          url: "clicky.php",
          data: {clicker:1} , <--- here goes the data that you want to send to your php file,  in this case SEND $_POST['clicker'] with value 1
          cache: false,
          success: <-- When is success your request, whats you want to make (other code) maybe print 'OK'
    }); 
}
</script>


<?php 
  if(isset($_POST['clicker'])) 
  { 
      mysqli_query($db,"UPDATE items SET this='that' WHERE number='1'")
  }
?>
Sign up to request clarification or add additional context in comments.

5 Comments

I'll give it a shot! Thank you!
its a bad practice to use same name for the ID attribute.
I'd say it is more than bad practice. It could cause errors in the script when trying to manipulate DOM.
Thanks for all the advice, I have one last question. I'm getting the ajax to query my db properly, but my echoed $likes php variable is not updating without a page reload - any ideas?
Are you actually setting the newly Ajaxed data in the element you want?
0

Try something like this:

$("#likeButtonID").click( function()
{
     $.ajax({  
        type: "POST",  
        url: "liker.php",  
        data: { like: $(this).val(); },
        success: function(result) {
            alert('Ajax Success Ran');
        }
   });
});

Or if you have many like buttons on a page you can do a jquery loop over each of them.

1 Comment

Thank you! I will try it out
0

WebMethod let act an ajax call like a webservice, no response are processed, class in json/xml format is returing (or nothing, just perform actions on server)

in AspNet is quite easy, try this if helps PHP Equivalent to Authorized ASP.NET WebMethod (AJAX)?

regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.