Passing data to javascript array to server with jQuery.ajax post function?

I was wondering if it is possible to transfer data stored in a javascript array to the server using the jQuery ajax function.

The jQuery documentation states:

$.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType }); 

Is it possible to set "data" to an array? How would this work be done, it seems that the data expects a pair of key values? I am currently just hardcoded values, but I want this to be a more dynamic approach. My current code is:

 jQuery.ajax({ url: "/createtrips/updateitin", type: 'POST', data: {place1: 'Sydney', place2: 'London'}, dataType: 'json', }); 
+7
source share
4 answers

I created an array like this:

 var placesfortrip = {}; 

then added to it as follows:

 placesfortrip["item"+counter] = inputVal; 

(where counter is an incremented counting variable) then assigned this to the data property to call ajax

  jQuery.ajax({ url: "/createtrips/updateitin", type: 'POST', data: placesfortrip, dataType: 'json', }); 

and if I look at the XHR tab in firebug, then these values ​​appear!

+8
source

Yes, jQuery.ajax() supports passing arrays. It simply serializes the array into a value-name string.

If the value is an array, jQuery serializes multiple values ​​with the same key based on the value of the traditional parameter (described below).

+2
source

I believe that you would like to learn about using JSON to pass these values.

This is a good place to start.

0
source

Complete jQuery serialization: http://api.jquery.com/serialize/

 $('form').submit(function() { alert($(this).serialize()); return false; }); This produces a standard-looking query string: a=1&b=2&c=3&d=4&e=5 
0
source

All Articles