I’m trying to insert the multiple lines of a text field to my database.
<html>
<head>
</head>
<body>
<table>
<tr>
<td><input type="text" id="name[0]" name="name[0]"></td>
<td><input type="text" id="grade[0]" name="grade[0]"></td>
</tr>
<tr>
<td><input type="text" id="name[1]" name="name[1]"></td>
<td><input type="text" id="grade[1]" name="grade[1]"></td>
</tr>
<tr>
<td><input type="text" id="name[2]" name="name[2]"></td>
<td><input type="text" id="grade[2]" name="grade[2]"></td>
</tr>
<tr>
<td><input type="text" id="name[3]" name="name[3]"></td>
<td><input type="text" id="grade[3]" name="grade[3]"></td>
</tr>
</table>
<input type="button" id="submit_in" name="submit_in" value="submit">
</body>
</html>
I put index to my id so that I can loop it using Ajax but I don’t know how to loop it and insert it using Ajax.
<script type="text/javascript">
$(document).ready(function(){
$('#submit_in').click(function() {
var stud_name = $('#name[0]').val();
var stud_grade = $('#grade[0]').val();
alert(stud_name+" "+stud_grade);
$.ajax({
type:"post",
url:"insert.php",
dataType:'json',
data:{'name':stud_name,'grade':stud_grade},
success:function(data){
}
});
});
});
</script>
And here is my PHP code:
<?php
$host = 'Localhost';
$username= 'root';
$password= '12345';
$db_name = 'multiple_ajax';
$con = mysql_connect($host,$username,$password) or die ("Cant Connect");
mysql_select_db($db_name) or die ("Cant Select DataBase");
error_reporting(E_ALL ^ E_NOTICE);
$name= $_POST['name'];
$grade = $_POST['grade'];
$insert = "INSERT INTO stud_info VALUES('$name','$grade')";
if(@!mysql_query($insert)){
die('error insert'.mysql_error());
}
?>
My PHP code has only two variables that would get using Ajax because I suppose that Ajax will loop that variables using the index in id. I’m new to Ajax and PHP
I’m sure you know that you can pass arrays through HTTP requests, right? Why are you doing requests one at a time? Concatenate all of them!
You will then have an array
GradeDatawith each element having a name and a grade. To pass it through AJAX, do it as follows:And from there, it’s a simple matter to recover it using PHP (it’ll come up as
$_POST['students']and the format of each element of the array will always be Array(‘grade’ => ‘something’, ‘name’ => ‘something’). From there, you just need to iterate and…that’s it!From there, inserting the rows is equally easy: