passing data in javascript array to server with jQuery.ajax post function?
Solution 1
I created an array like this:
var placesfortrip = {};
then added to it like this:
placesfortrip["item"+counter] = inputVal;
(where counter
is an incremented counter variable)
then assigned this to the data
property of the ajax call
jQuery.ajax({
url: "/createtrips/updateitin",
type: 'POST',
data: placesfortrip,
dataType: 'json',
});
and if I look at the XHR tab in firebug it appears those values get posted!
Solution 2
Yes, jQuery.ajax()
supports the passing of arrays. It simply serializes the array into a name-value string.
If value is an Array, jQuery serializes multiple values with same key based on the value of the
traditional
setting (described below).
Rowan
Updated on June 09, 2022Comments
-
Rowan almost 2 years
I was wondering if its possible to pass data stored in a javascript array to the server using jQuery's ajax function..
In the jQuery documentation it specifies:
$.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType });
can "data" be set to an array? How would this work given it seems data is expecting key value pairs? I currently just hard code the values but I want it to be a more dynamic approach..my current code is:
jQuery.ajax({ url: "/createtrips/updateitin", type: 'POST', data: {place1: 'Sydney', place2: 'London'}, dataType: 'json', });
-
Rowan over 12 yearsDo you have an example? It doesn't seem to support serialize (?)
-
Rowan over 12 yearsI created an array like this: