2013-05-08 80 views
1

我一直在嘗試幾個小時才能使其工作,並未移動預算。Ajax/jquery如何從按鈕點擊發送數據而無需刷新頁面

什麼即時試圖做的是發送按鈕時點擊一個網址,但無需刷新頁面按鈕

PHP代碼:

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

jQuery代碼:

<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'"); 

?> 

我刪除了所有來自votehandler.php的錯誤檢查,試圖得到任何迴應,但迄今爲止沒有。

歡迎任何建議,試圖瞭解jQuery/ajax。

回答

5

兩個問題與您的代碼:

  • jQuery選擇不工作。正確的是:'a[class="approve-button"]'
  • 該代碼應該被包裝在jquery ready()函數中,以確保在JavaScript代碼執行之前DOM(帶有鏈接)已經被加載。

又來了一個工作示例:

$(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"); 
     } 
    }); 

}); 

}); 
+0

非常感謝你,是固定的問題。 – user2360599 2013-05-08 02:56:24

+0

沒問題:) – hek2mgl 2013-05-08 02:57:34

相關問題