Add Javascript array to POST variable in submit form

I have a Javascript array that I would like to add to the message array when submitting the form. A Javascript array should be added in addition to other variables already submitted from the form. Is there a way to do this in jQuery?

Ref.

the 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> 

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

 Array ( [first_name] => John [last_name] => Smith [external_ids]=> ( [SSN] => 555-55-5555 [PID] => GBNT22 ) ) 
+4
source share
2 answers

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 .

+2
source

JQuery has a serialize () function. Have you checked 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
source

All Articles