I'm trying to insert array value in php passing through ajax, but I am not succeeding. I think the problem is in ajax while sending array variable. My HTML form is as below.
<tr>
<th>ID</th>
<td><input type="number" id="navid"></td>
</tr>
<tr>
<th>Menu NPL</th>
<td><input type="text" name="menunpl[]"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng[]"></input>
</td>
</tr>
And I've passed value as
$("#submit").click(function(){
var navid = $("#navid").val();
var menunpl = $("input[name='menunpl[]']" ).val()
var menueng = $("input[name='menueng[]']" ).val()
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {navid:navid,menunpl:menunpl,menueng:menueng},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});
But In serverside, it says Invalid argument supplied for foreach()
if (isset($_POST["navid"]) && !empty($_POST["navid"])) {
foreach ($_POST['menunpl'] AS $key => $item){
$query1 =$con->prepare("INSERT INTO menu(cid, title, en_title) VALUES (:navid, :menunpl, :menueng)");
$query1->bindParam(':menunpl',$item);
$query1->bindParam(':menueng',$_POST["menueng"][$key]);
$query1->bindParam(':navid', $_POST["navid"]);
$query1->execute();
$msg1 = 'Menu has inserted';
}
}
foreachover a string in PHP? I'm fairly certain from what you have shown that$_POST['menunpl']would be a string.ajax. In this way you can't pass array variable. Changevar menunpl = $("input[name='menunpl[]']" ).val()tovar menunpl = []; $('input[name="menunpl[]"]').each( function() {menunpl.push(this.value);});and other variable as this. This should work. And do not forget to add array toidin html and ajax.