6

I have a Javascript array that I would like to add to the post array when a form is submitted. The Javascript array should be added in addition to other variables already being posted from the form. Is there a way to do this in JQuery?

Ex.

Form:

<form id="my-form" action="/create.php" method="post">
<input id="first_name" type="text" /> 
<input id="last_name" type="text" /> 
</form>

Javascript array:

<script type="text/javascript">

var external_ids = [{"name":"SSN","value":"555-55-5555"},    
{"name":"PID","value":"GBNT22"}];

</script> 

This is what I would like the resulting PHP $_POST array to look like, if possible:

Array
(
    [first_name] => John
    [last_name] => Smith
    [external_ids]=>
        (
            [SSN] => 555-55-5555
            [PID] => GBNT22
        )
)
1

2 Answers 2

2

There you go:

var external_ids = [{"name": "SSN", "value": "555-55-5555"},
                    {"name": "PID", "value": "GBNT22"}];

// form fields
var values = {};
var fields = $('#myForm :input');
$.each(fields, function(i, field) {
    var dom = $(field),
        name = dom.attr('id'),
        value = dom.val();
    values[name] = value;
});

// add array
values.external_ids = {};
$.each(external_ids, function(i, field) {
    values.external_ids[field.name] = field.value;
});

// post data
$.post('/endpoint', values);​

Find the code in this jsfiddle as well.

Sign up to request clarification or add additional context in comments.

Comments

1

There is the serialize() function on jQuery. Had you check this?

Or you can use something like this:

function onSubmit(){
    var toSend = [
        first_name : 'John',
        last_name : 'Smith',
        external_ids : {
            SSN: '555-55-5555',
            PID: 'GBNT22'
        }
    ];

    $.post( yourUrl, toSend, function(data){
        //callback
    } );

}

1 Comment

How would this look in a JQuery event handler?

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.