0

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.

3 Answers 3

2

Use:

var postData = $("#formId").serializeArray();
$.post(url, postData, function(response){ //do something });
Sign up to request clarification or add additional context in comments.

Comments

1

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){ ... });

3 Comments

first of all thanks a lot for all the suggestions provided. So I made few changes and got what i wanted. I add class attribute to input elements as "mc". So I can use data={mc: $('.mc').serialize()} and on php side parse_str($_POST['data']['mc']);print_r($field);
Can this be further improved or can there be any serious errors? Please suggest. Thanks.
@user2987833: if you just want to serialize the full form and send it, go with @Ramesh' answer. you won't need to use parse_str on PHP side.
0

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 })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.