2017-03-03 119 views
-1

我有jQuery獲取多個複選框的值。jQuery通過多個複選框值使用Ajax的PHP到

您可以參考的演示here

爲jQuery的功能是確定的,當我們勾選複選框,然後我們可以看到我們選擇基於btnUpdate點擊後數據-ID。

但現在我想通過並將其存儲到數據庫使用Ajax的PHP。 所以示例輸出,

1 -> read 
1 -> update 
2 -> update 

然後將其保存到數據庫中的表:

ID | chkStatus 
1 | read 
1 | update 
2 | update 

下面是HTML

<table> 
<tr> 
    <th>Nama</th> 
    <th>Create</th> 
    <th>Read</th> 
    <th>Update</th> 
    <th>Delete</th> 
</tr> 
<tr> 
    <td>coba</td> 
    <td><input type="checkbox" data-id="1" data-tipe="create"></td> 
    <td><input type="checkbox" data-id="1" data-tipe="read"></td> 
    <td><input type="checkbox" data-id="1" data-tipe="update"></td> 
    <td><input type="checkbox" data-id="1" data-tipe="delete"></td> 
</tr> 
<tr> 
    <td>coba 2</td> 
    <td><input type="checkbox" data-id="2" data-tipe="create"></td> 
    <td><input type="checkbox" data-id="2" data-tipe="read"></td> 
    <td><input type="checkbox" data-id="2" data-tipe="update"></td> 
    <td><input type="checkbox" data-id="2" data-tipe="delete"></td> 
</tr> 
<tr> 
    <td><input type="button" id="btnUpdate" value="Update"/> 
</tr> 

jQuery的

$(function(){ 
    $('#btnUpdate').click(function(){ 
    var cb = []; 
    $.each($('input[type=checkbox]:checked'), function(){ 
     cb.push($(this).data('id') + ' -> ' +$(this).data('tipe')); 
    }); 
    $('#status').val(cb.join("\n")); 
    }) 
}); 
+0

http://stackoverflow.com/questions/42530480/how-do-i-pass-jquery-value-to-php/42531178#42531178 –

+2

[用PHP jQuery的Ajax的POST示例](的可能的複製HTTP ://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) –

回答

1

您可以通過同時發送陣列服務器端獲取或交的,你的情況在這裏我建議修改你如何構建陣列記:

$(function(){ 
    $('#btnUpdate').click(function(){ 
     var cb = [], 
      post_cb = [] 

     $.each($('input[type=checkbox]:checked'), function(){ 
      var id = $(this).data('id'), 
       tipe = $(this).data('tipe') 

      cb.push(id + ' -> ' + tipe); 
      post_cb.push({ 
       'id': id, 
       'tipe': tipe 
      }); 
     }); 
     $('#status').val(cb.join("\n")); 

     $.ajax({ 
      'type': 'post', 
      'url': '/path/to/script.php', 
      'data': { 
       'cb': post_cb 
      }, 
      'success': function(response) { 
       // Do something 
      }, 
      'error': function(response) { 
       // Do something 
      } 
     }); 
    }) 
}); 

然後在你的PHP文件:

<?php 

print_r($_POST['cb']); 
/* 

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [tipe] => read 
     ) 

    [1] => Array 
     (
      [id] => 1 
      [tipe] => update 
     ) 

    [2] => Array 
     (
      [id] => 2 
      [tipe] => update 
     ) 

) 

*/ 

?> 
+0

感謝您的回答,浩把它存儲到數據庫?如果我有表格列:ID | CHKVALUE –

+0

您使用的是哪種數據庫技術? MySQL的?我在問,因爲根據數據庫的不同,你使用的PHP函數會有所不同 – Scoots

+0

Hi Scoots,我正在使用Oracle DB –