简体   繁体   中英

Pass checkbox values to php script page jquery

I have a following code it is getting the values of checked checkboxes and submit the data on button click.Pls look into the code and do let me where i am wrong.It is not working

$(document).ready(function() {
$(function(){
  $('#btnClick').click(function(){
    var val = [];
    $(':checkbox:checked').each(function(i){
      val[i] = $(this).val();
      $.ajax({
            url: 'server.php',
            type: "POST",
           data: ({val[i]}), ????
           success: function(data){

            }
        });


    });
  });
});
});

It's easier to use serialize , it's designed for exactly this kind of situation.

$(function(){
  $('#btnClick').click(function(){
   var val = $('input[type=checkbox]:checked').serialize();
   $.ajax({
        url: 'server.php',
        type: "POST",
        data: val,
        success: function(data){

        }
    });

   });
 });

Also it's better to use $(input[type=checkbox]:checked) as the selector instead of $(':checkbox:checked') . From the jQuery docs:

$(':checkbox') is equivalent to $('[type=checkbox]'). As with other pseudo-class selectors (those that begin with a ":") it is recommended to precede it with a tag name or some other selector; otherwise, the universal selector (" ") is implied. In other words, the bare $(':checkbox') is equivalent to $(' :checkbox'), so $('input:checkbox') should be used instead.

Because :checkbox is a jQuery extension and not part of the CSS specification, queries using :checkbox cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. For better performance in modern browsers, use [type="checkbox"] instead.

  • Keep the ajax function outside the each loop.
  • $(function(){}) & $(document).ready(function(){}) are one and the same. The former is a shorthand form.

     $(function(){ var val[], i=0; $('#btnClick').click(function(){ $('input:checkbox:checked').each(function(){ val[i] = $(this).val(); i++; }); $.ajax({ url: 'server.php', type: "POST", data: {'checked_values':val}, success: function(data){ // do something with returned data } }); }); }); 

In server.php page

$checked = $_POST['checked_values']; // will contain an array with checked values
// proceed to do something with $checked array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM