Reputation: 413
My form contains hidden input looping. in my case, i declare the hidden input in ajax data manually without looping. so how to loop them in ajax data?
here's my form script
<form method="POST" name="myform">
<?php for($i=1;$i<=5;$i++) { ?>
<input type="hidden" name="data<?php echo $i; ?>" value="data<?php echo $i; ?>">
<?php } ?>
<input type='button' name='submitData' value='Submit' onClick='submitData();'>
</form>
here's my Ajax script
function submitData() {
var form = document.myform;
$.ajax({
url: 'process.php',
type: 'post',
data: {
data1 : form["data1"].value,
data2 : form["data2"].value,
data3 : form["data3"].value,
data4 : form["data4"].value,
data5 : form["data5"].value
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
}
Upvotes: 3
Views: 2345
Reputation: 20626
Your hidden inputs have name and values,
use .serialize()
Encode a set of form elements as a string for submission
data : $('form[name=myform]').serialize()
This will return name=value
pairs.
If you need {name:value}
, use .each()
var formData = {}
$('form :input:hidden[name^="data"]').each(function(){
formData[this.name] = this.value;
});
And in ajax,
data : formData ,
Upvotes: 3
Reputation: 12004
Also, a good way to do it is to convert the string to JSON object, and in PHP convert the string in an array:
var dataJSON = JSON.stringify({..Your form obj...});
$.ajax({
url: 'process.php',
type: 'post',
data: dataJSON,
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
process.php
$data = json_decode($_POST["data"]);
print_r($data);
Upvotes: 1
Reputation: 6852
If you're posting the whole form, you can use jQuery's .serialize() directly in your request:
$.ajax({
url: 'process.php',
type: 'post',
data: $('#myform').serialize(),
...
Upvotes: 2