Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 803
Ben Avatar asked Apr 21 '12 16:04

Ben


People also ask

Can we send array through AJAX?

Note – You can pass JavaScript Array variable as same as any other variable in AJAX request.

How do you send an array of objects?

Passing array of objects as parameter in C++ Array of Objects:It is an array whose elements are of the class type. It can be declared as an array of any datatype. Syntax: classname array_name [size];

Can we send multiple data in AJAX?

send multiple data using ajax ajax({ url: "/pakainfo_api", type: "GET", data: {p1: "value1", p2: "value2"}, // multiple data we want to send success: function(data){ console. log(data); } }). done(function(){ console. log("Success."); }).

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.


2 Answers

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()!

like image 58
noob Avatar answered Oct 02 '22 04:10

noob


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/

like image 34
Chris Baker Avatar answered Oct 02 '22 02:10

Chris Baker