2014-10-20 29 views
0

我無法刪除數據庫中的記錄,取回代碼正在工作,但刪除代碼不起作用。請幫我..謝謝提前用ajax刪除數據

代碼與AJAX獲取數據

$(document).ready(function(){ 
     done(); 
    }); 
    function done(){ 
     setTimeout(function(){ 
      updates(); 
      done(); 
      }, 200); 
    } 

    function updates(){ 
     $.getJSON("fetch.php",function(data){ 
      $("table").empty(); 
      $("table").append("<tr><td>Name</td><td>Date</td><td>Delete</td></tr>"); 
      $.each(data.result, function(){ 
       $("table").append("<tr><td>"+this['text']+"</td><td>"+this['date']+"</td><td><a id='del' href='"+this['id']+"'>Del</a></td></tr>"); 
      }); 
     }); 
    } 

代碼使用Ajax來刪除數據

 $(function() { 
    $("#del").click(function(){ 
    var element = $(this); 
    var id = element.attr("id"); 
    var dataString = 'id=' + id; 
    if(confirm("Sure you want to delete this comment?")) 
    { 
     $.ajax({ 
     type: "GET", 
     url: "del.php", 
     data: dataString, 
     success: function(){ 

      } 
     }); 
    } 
    return false; 
    }); 

}); 

PHP代碼del.php

$last_page_id = $_REQUEST['d_i_d']; 
$sql = mysql_query("delete from time where id = '{$last_page_id}'"); 

if(!$sql){ 
    echo mysql_error(); 
}else{ 
    header('location: index.php'); 
} 
+1

我們需要del.php頁面的php代碼來幫助您。 – Superdrac 2014-10-20 12:07:42

+0

'del.php'中的郵政編碼也 – 2014-10-20 12:07:45

+0

曾經認爲這個問題可能存在於你的SQL中?作爲和/或? – 2014-10-20 12:07:58

回答

1

阿賈克斯數據:dataString = 'id=' + id;

調用它在PHP:$last_page_id = $_REQUEST['d_i_d'];

你可以得到的ID與$_REQUEST['id']

請注意,mysql_被棄用:Why shouldn't I use mysql_* functions in PHP?

而且你的代碼是開放的到SQL注入:http://en.wikipedia.org/wiki/SQL_injection

+1

我說['5分鐘之前'](http://stackoverflow.com/questions/26465335/delete-data-with-ajax#comment41568714_26465335)等待OP的迴應。 – 2014-10-20 12:18:31

+2

['現在你明白了爲什麼'](http:// stackoverflow。com/questions/26465335/delete-data-with-ajax#comment41568982_26465335)我首先使用註釋來確保。 – 2014-10-20 12:27:07

+0

哈哈,在那裏得到了一個點。注意到這個明顯的錯誤讓我忽略了另一個錯誤。然而,它只花了我5分鐘來獲得文章中的鏈接(不得不查看它們),所以基本上我們只是通過一種不同的方法來回答相同的答案,我並沒有模仿你的評論。 – nvanesch 2014-10-20 12:33:53

0

嘗試傳遞這樣的數據:

$.ajax{ 
    url: 'del.php', 
    method: 'GET', 
    data: { 
     id: // Put your ID value here 
    } 
    success: function(){ 
     // Put your success code here 
    } 
} 

看那個片段:

$("#del").click(function(){ 
var element = $(this); 
var id = element.attr("id"); 
... 

id變量會一直持有 「德爾」 的價值,因爲你得到的$ ID ATTR( '#德爾')。

+0

先生我的這行代碼是好的....請指導我 Del Mani 2014-10-20 12:31:32

+0

[文檔](http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings)sais東西不同的類型:PlainObject或String或Array我不認爲它是錯誤的,但它不是問題:) – VDP 2014-10-20 12:32:17

+0

作爲對象或字符串傳遞不是問題,但關於alweays發送「del」值的部分是真正。 @Mani on the html你應該使用'.attr('href')' – nvanesch 2014-10-20 12:43:12