Reputation: 3
I have a form with array of input elements as shown below.
<form method="post" action="sample.php">
<input type="text" name="field[txt][name]" />
<input type="text" name="field[txt][sex]" />
<input type="text" name="field[txt][location]" />
<br /><br />
<input type="text" name="field[num][age]" />
<input type="text" name="field[date][pod]" />
<input type="text" name="field[date][doj]" />
<br /><br />
<input type="submit" name="submit" />
</form>
php - print_r($_POST['field']) gives me an output similar to the following when i submit the form as usual. How can I use jquery-post method to submit 'field[ ][ ]' element to get the same result?
Array(
[txt] => Array
(
[name] => sam
[sex] => male
[location] => somewhere
)
[num] => Array
(
[age] => 20
)
[date] => Array
(
[pob] => 2001-01-01
[doj] => 2001-01-01
)
)
Any help would be highly appreciated.
Upvotes: 0
Views: 386
Reputation: 349
try jquery .Serializre()
var values = $("form").first().serialize();
This code will get all values and serialize to Url Data like it: "&field[txt][name]=foo1&field[txt][sex]=male"
then you use the Ajax:
$.ajax({url: $("form").first().attr("action"), data: values })
Upvotes: 0
Reputation: 4293
Use:
var postData = $("#formId").serializeArray();
$.post(url, postData, function(response){ //do something });
Upvotes: 2
Reputation: 51922
You can use a regular javascript object as a data
parameter, and jQuery will take care to serialize it as an url parameter :
var data = {
fields: {
txt: {
name: "sam",
sex: "male",
location: "somewhere"
},
num: {
age: 20
},
date: {
pob: "2001-01-01",
doj: "2001-01-01"
}
}
};
$.post(url, data, function(answer){ ... });
Upvotes: 1