I want to send multiple inputs(one is text and one is select multiple
) via AJAX to a PHP file. Data is sended correctly with form serialize, in fact, using console.log, it shows that prod_multi
is a complete array with the selected options. The problem is when I try to store the array values of prod_multi
in a variable; if I echo the variable, it is empty. Could you plese help me to solve this issue?
Here's the code.
HTML
<form id="form_menu">
<div >
<div >
<div >
<label for="forms-check-name">Name *</label>
<input id="forms-check-name" type="text" name="name_menu" placeholder="Name" required>
</div>
</div>
<div >
<div >
<label for="involve-form-product">Products *</label>
<select id="involve-form-product" name="prod_multi" multiple required>
<option disabled="disabled" >Products</option>
<option>Prod A</option>
<option>Prod B</option>
<option>Prod C</option>
<option>Prod D</option>
</select>
</div>
</div>
<div >
<input type="submit" value="Add" id="add_menu" name="add_menu">
</div>
</div>
</form>
AJAX
$(document).on('click','#add_menu',function (e) {
var form = $('#form_menu').serialize();
e.preventDefault();
$.ajax({
type: "POST",
url: "file.php",
data: form,
cache: false,
success: function()
{
alert("Ok");
},
error: function()
{
alert("Not ok");
}
});
});
PHP
$array=$_POST["prod_multi"];
$array_length=count($array);
$list=NULL;
$i=0;
foreach($array as $prod)
{
if( $i == $array_length)
{
$list=$list . $prod;
}
else
{
$list=$list . $prod . ', ';
}
$i ;
}
Thank you for your help.
CodePudding user response:
Adding the brackets will help PHP process the data correctly
name="prod_multi[]"