1

ive been trying for hours to get this to work and havent moved a budge.

What im trying to do is send an url when a button is click, but without refreshing the page

php code of button:

    echo '<a href="#" class="approve-button" id="'.$link_url[link_url].'">Send</a>';

jquery code:

<script type="text/javascript">

//Attach an onclick handler to each of your buttons that are meant to "approve"
$('approve-button').click(function(){

   //Get the ID of the button that was clicked on
   var id_of_item_to_approve = $(this).attr("id");


   $.ajax({
      url: "votehandler.php", //This is the page where you will handle your SQL insert
      type: "POST",
      data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
      success: function(){
          console.log("AJAX request was successfull");
      },
      error:function(){
          console.log("AJAX request was a failure");
      }   
    });

});

</script>

votehandler.php:

<?php

    $data = $_POST['id'];
    mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");

?>

Ive removed all the error checks from votehandler.php to try to get any response but so far nothing.

any advice is welcome, trying to understand jquery/ajax.

1 Answer 1

5

Two problems with your code:

  • The jquery selector isn't working. Correct is: 'a[class="approve-button"]'
  • The code should being wrapped within the jquery ready() function to make sure that the DOM (with the links) has already been loaded before the javascript code executes.

Here comes a working example:

$(function() { // wrap inside the jquery ready() function

//Attach an onclick handler to each of your buttons that are meant to "approve"
$('a[class="approve-button"]').click(function(){

   //Get the ID of the button that was clicked on
   var id_of_item_to_approve = $(this).attr("id");


   $.ajax({
      url: "votehandler.php", //This is the page where you will handle your SQL insert
      type: "POST",
      data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
      success: function(){
          console.log("AJAX request was successfull");
      },
      error:function(){
          console.log("AJAX request was a failure");
      }   
    });

});

});
Sign up to request clarification or add additional context in comments.

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.