Ben
Ben

Reputation: 157

Sending an array of objects as ajax post data?

My overall goal is to get all some of all drop-downs on a page and send that to be processed by a php file.

Right now, the way I'm doing it in jQuery is making an overall schedule array and then adding each element to be updated to that array. So I have something like:

var schedule = [];
var data = { 
   'user_id' : '12', 
   'day_of_week' : 'Monday',
    'when' : 'start',
    'time' : '12 AM'
 }
schedule.push(data);
var data = { 
   'user_id' : '13', 
   'day_of_week' : 'Tuesday',
    'when' : 'end',
    'time' : '12 AM'
 }
schedule.push(data);
// schedule would have two objects in it

Obviously in loops and and stuff.

So, my schedule array has two objects in it, in this case.

Now, is it possible to use that schedule array as the ajax data? It doesn't work if I do something like:

$.ajax({
  url: 'http://something.com/ajax',
  data: schedule,
  type: 'POST'
});

But if I instead change it to schedule[0] it works just fine, but only for the first thing in the schedule array, obviously.

Upvotes: 11

Views: 71014

Answers (3)

Chris Baker
Chris Baker

Reputation: 50592

Make sure you are using the correct version of jQuery. In earlier versions, you had to pass a sting; new versions use "intelligent guess" on the data variable. You can either explicitly tell jQuery that you're passing it a javascript object with the dataType parameter, or you can let jQuery figure it out.

Documentation

jQuery.ajax() - http://api.jquery.com/jQuery.ajax/

Upvotes: 3

noob
noob

Reputation: 9202

The data attribute should be an object.

What you can do is this:

$.ajax({
  url: 'http://something.com/ajax',
  data: {schedule: schedule},
  type: 'POST'
});

So if you receive this for example in PHP you have $_POST["schedule"]. An that is exactly the same as you had in JavaScript.

Ohh yes I've forgot... also have a look at .serialize() and .serializeArray()!

Upvotes: 11

Madara's Ghost
Madara's Ghost

Reputation: 174957

Pass it as JSON:

$.ajax({
  url: 'http://something.com/ajax',
  data: {schedule: schedule},
  type: 'POST',
  dataType: 'JSON'
});

It would send a JSON encoded string to the server, which server-side languages can parse. (in PHP, it's done with json_decode()).

Upvotes: 2

Related Questions