开发者

How to pass multiple checkboxes to PHP through JQUERY

I HAVE modified my code, i used firebug console.log to detect weather the the php gets the array passed or not. and firebug displays this - rescheck[]=2&rescheck=1&rescheck=3

I think php gets the array if THATS what an array in php supposed to be like.

SO guys, if thats correct how to insert that array in database? or how to loop it? the foreach loop ive made didnt work.

JQUERY CODE:

$('#res-button').click(function (){

var room_id=$('[name=rescheck[]]:checked').serialize().replace(/%5B%5D/g,'[]');

    alert(room_id);


  $.ajax({
                    type: "POST",
                    url: "reservation-valid.php",
                    data: {name_r:name_r, email_r:email_r,contact_r:contact_r,prop_id:p_id,cvalue:room_id},
                    success: function(data) {

                    console.log(data);
}

});
});

<input type="checkbox" name="rescheck[]" value="<?php echo $roomid; ?>"  />

PHP CODE:

$c_array=$_POST['cvalue'];

    echo $c_array;

    //foreach($c_array as $ch)
    //{
    //$sql=mysql_query("INSERT INTO reservation VALUES('','$prop_id','$ch','$name_r','$contact_r','$email_r','')");
    //}
开发者_如何转开发

I think I managed my jquery code to be right, but I don't know how to fetch that with PHP.


room_id is an array, so if you want to get the value for each, you need to get all value together first.

var room_id_string = '';

for(i=0;i<room_id.length;i++){
    room_id_string += room_id.eq(i).val() + ',';
}


your below code will only pass Array jquery object of [name=rescheck[]]:checked to room_id

Instead of this you will have to create a array and push values in it like this

var room_id = Array();

$('[name=rescheck[]]:checked').each(function(){
      room_id.push($(this).val());

});


In jQuery it might be easier for you to just use the serialize function to get all the form data. jQuery passes the form to the server so you don't have to worry about getting all the values. If you use it in conjunction with the validate plugin you might find it a little easier!

http://bassistance.de/jquery-plugins/jquery-plugin-validation/


This is what I do ibn my site for saving to a db a list of checkboxes with jquery and ajax call. It make an array and pass it to the ajax call and the php script handle the array. If you get any error here you should debug the js array with firebug for be sure that is formed correctly.

js script:

var $checkBox = $('[name=rescheck[]]:checked');
$checkBox.each(function() {
   if ($(this).is(":checked")){
        valuesCheck[this.value] = 1;
    }else{
        valuesCheck[this.value] = 0;    
   }

and the PHP script:

$checkTab = $_POST['cvalue'];
        foreach ($checkTab as $idChkTab => $checkedOrNot){
            if ($checkedOrNot== "0"){
                //do something if isn't checked
            }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜