Ajax and PHP to Enter Multiple Forms Input to Database

How to handle multiple form data via ajax to php

To submit multiple fields with the same name in a HTML form you need to use array syntax in the name attributes:

<input type="text" value="2021-05-01" class="date" name="startdate[]">                        
<input type="text" value="10:00" class="starttime" name="starttime[]">
<input type="text" value="17:00" class="endtime" name="endtime[]">
<input type="text" value="7" class="hours" name="total[]">

<input type="text" value="2021-05-02" class="date" name="startdate[]">
<input type="text" value="11:00" class="starttime" name="starttime[]">
<input type="text" value="17:00" class="endtime" name="endtime[]">
<input type="text" value="6" class="hours" name="total[]">

Then in the jQuery, rather than pulling out each field individually, just have jQuery serialize the whole form automatically for you:

data: $("#form").serialize()

(Obviously replace the "#form" selector with the real ID of your form - it's not visible in your question so I can't use it here.)

This will get you a multi-dimensional array of values in $_POST on the server-side.

How to insert multiple inputs with same name in php through ajax

You have to apply array in input field for multiple input element. And pass array through ajax and insert to database using foreach loop.

HTML

<tr>
<th>ID</th>
<input type="number" name="navid[]" id="navid">
</tr>
<tr>
<th>Menu IN</th>
<td><input type="text" name="menuin[]"></input></td>
</tr>
<tr>
<th>Menu ENG</th>
<td><input type="text" name="menueng[]"></input>
</td>
</tr>

Ajax

$("#submit").click(function(){
var navid = [];
$('input[name="navid[]"]').each( function() {
navid.push(this.value);
});
var menuin = [];
$('input[name="menuin[]"]').each( function() {
menuin.push(this.value);
});
var menueng = [];
$('input[name="menueng[]"]').each( function() {
menueng.push(this.value);
});
$.ajax({
url: 'insert_nav.php',
type: 'post',
data: {navid:navid,menuin:menuin,menueng:menueng},
success: function(data){
alert(data);
$('#nav')[0].reset();
}
});
});

PHP

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


Related Topics



Leave a reply



Submit