Dipak
Dipak

Reputation: 939

how to pass checkbox array to php from FormData

Checkbox array can not pass to php through ajax in case of FormData. Following script is working fine where FormData hasn't been used. So I assume problem is in while appending in FormData or passing from it. It returns invalid arguments supplied for foreach().

Checkbox is not part of form element, so

  <input type="checkbox" id="menu" name="menu[]" value="1">
  <input type="checkbox" id="menu" name="menu[]" value="2">
  <input type="checkbox" id="menu" name="menu[]" value="3">

  <form id="form">
  ...........
  </form>

Jquery and ajax

$(document).on('submit', '#form', function(e){
    e.preventDefault();
    var navid = [];
        $("[name='menu[]']:checked").each(function (i) {
        navid[i] = $(this).val();
    });
    if (navid.length === 0){ //tell you if the array is empty
        alert("Please Select atleast one checkbox");
    }
    else {
    var formData = new FormData(this);
    formData.append('navid', navid);
    $.ajax({
        type: 'POST',
        url: 'upload.php',
        data: formData,
        contentType: false,
        cache: false,
        processData:false,
        success: function(data){
            alert(data);
        }
    });
    }
});

PHP

foreach ($_POST["navid"] AS $key => $item){               
    $query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
    $query1->bindParam(':menunin',$_POST["menunin"][$key]);
    $query1->bindParam(':menueng',$_POST["menueng"][$key]);
    $query1->bindParam(':navid',$item);
    $query1->execute();
    echo 'Menu has inserted';     
}

Upvotes: 1

Views: 2401

Answers (1)

Bhumi Shah
Bhumi Shah

Reputation: 9476

Yes issue in your php code:

You are passing comma seperated values so first explode and use

$data = explode("," ,$_POST["navid"]);
foreach ($data AS $key => $item){
    $query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menuin, :menueng)");
    $query1->bindParam(':menunin',$_POST["menunin"][$key]);
    $query1->bindParam(':menueng',$_POST["menueng"][$key]);
    $query1->bindParam(':navid',$item);
    $query1->execute();
    echo 'Menu has inserted';
}

Upvotes: 1

Related Questions