2016-07-01 34 views
0

我想刪除動態創建的記錄,從一個動態創建的形式,刪除記錄,但代碼不working..Please看看使用AJAX和PHP

的script.js

$(function() { 

      $('#studentRecord').on('click', 'button.delete', function() { 

      var $tr = $(this).closest('tr'); 

      var $id = parseInt($(this).attr('id').split('-')[1]); 


      if (confirm("Are you sure you want to delete this record")) { 

       $.ajax({ 
        url: '/ab_batch/practice/db/action.php', 
        type: 'POST', 
        data: { 
         action: 'ajaxDelRecord', 
         id: JSON.stringify(id) 
        }, 

        success: function() {}, 


        error: function() {} 

       }); 

      } 


     }); 


    }); 

action.php的

$action = (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) ? $_REQUEST['action'] : null; 
switch ($action) { 
case 'ajaxDelRecord': 

     if (isset($_POST['id'])) { 
      $id = json_decode($_POST['id']); 
     } 

     $id = json_decode($_POST['id']); 
     print ($student->delRecord($id)) ? 'true' : 'false' ; 

     break; 

} 

有一個包含刪除所有API另一個db.php文件,添加和更新

+0

''JSON.stringify(id)'應該是'JSON.stringify($ id)',因爲您將'id'聲明爲'$ id',您並不需要:'JSON.stringify'只是發送一個整數到服務器。 –

+0

@ArshSingh非常感謝它的工作,但頁面需要重新加載才能查看結果...因爲我使用ajax不應該結果反映一旦我點擊刪除按鈕? –

+0

您應該在服務器回答您的ajax請求後刪除div。它不會反映變化,直到你沒有說要通過發送請求到服務器刪除你最近刪除的特定html元素 –

回答

3

JSON.stringify(id)應該是JSON.stringify($ id),因爲你聲明你的id爲$ id,你並不需要:JSON.stringify,因爲你只是發送一個整數給服務器。

,並刪除您剛剛從數據庫中刪除行了,你可以用下面的代碼替換您的JavaScript代碼:

$(function() { 

      $('#studentRecord').on('click', 'button.delete', function() { 

      var $tr = $(this).closest('tr'); 

      var $id = parseInt($(this).attr('id').split('-')[1]); 


      if (confirm("Are you sure you want to delete this record")) { 

       $.ajax({ 
        url: '/ab_batch/practice/db/action.php', 
        type: 'POST', 
        data: { 
         action: 'ajaxDelRecord', 
         id: JSON.stringify($id) 
        }, 

        success: function() {}, 

         $tr.remove(); // removing the current deleted record from html. 
        error: function() {} 

       }); 

      } 


     }); 


    }); 

我沒有添加$tr.remove();一個成功回調裏面,因爲你已經宣佈的父元素的刪除記錄,所以你只需要使用:$tr.remove();刪除tr。

+0

它的工作....但如果我刪除最高的記錄有序列號1頁面不會自動替換下一個記錄與序列號1 ...而是第二個記錄有一個序列號2,只有在刷新其顯示序列號1 ...有沒有辦法?希望我不會打擾你太多 –

+0

爲什麼不自動刷新頁面後記錄被刪除,所以你看到直接的結果,我的意思是:在'$ tr.remove();'後面加'location.reload();'。如果它對你有幫助,請考慮接受爲答案。謝謝。 –