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
PHP - How to Create a Newline Character
Send File Attachment from Form Using PHPmailer and PHP
Using $_Post to Get Select Option Value from Html
Isset() and Empty() - What to Use
Sorting an Associative Array in PHP
Convert Command Line Curl to PHP Curl
PHP Simplexml How to Save the File in a Formatted Way
How to Add Http:// If It Doesn't Exist in the Url
How to Post Json to PHP With Curl
MySQLi: Can It Prepare Multiple Queries in One Statement
Insert Array into MySQL Database With PHP
What Does $$ (Dollar Dollar or Double Dollar) Mean in PHP
How to Increase the Execution Timeout in PHP