Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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',
            });
like image 608
Rowan Avatar asked Dec 25 '11 21:12

Rowan


People also ask

Can ajax send data to server?

Ajax (Asynchronous JavaScript And XML) allows web pages to be updated asynchronously by exchanging data to and from the server. This means you can update parts of a web page without reloading the complete web page.

Does ajax use POST?

post() makes Ajax requests using the HTTP POST method. The basic syntax of these methods can be given with: $. get(URL, data, success); —Or— $.

What is difference between ajax and POST?

$. post is a shorthand way of using $. ajax for POST requests, so there isn't a great deal of difference between using the two - they are both made possible using the same underlying code.

How do I pass a php array to ajax jQuery?

if you would like to send 2 array via ajax, you can create a new array like this: <? php echo json_encode(array( 'issues' => $issue, 'foo' => $foo, )); ?>


1 Answers

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!

like image 185
Rowan Avatar answered Sep 17 '22 18:09

Rowan