24

Am wondering how to post an array using $.ajax. My array is something like this:

var a = new Array();
a['test'] = 1;
a['test2'] = 2;
and so on...

I tried:

$.ajax({
  url: baseUrl+"chat.php",
  data: { vars: a},
  type: 'post',
  success: function(data) {
alert(data);
}});

Any suggestions?

2
  • Nothing looks obviously wrong, how are you trying to access the data in the php? Commented Jun 4, 2009 at 13:51
  • And have you used some kind of traffic watch to make sure the call is getting to the chat.php page? Commented Jun 4, 2009 at 13:53

5 Answers 5

43

Try this one:

var a = {};
a['test'] = 1;
a['test2'] = 2;

// or


var a = {};
a.test = 1;
a.test2 = 2;

// or


var a = {
    test : 1,
    test2 : 2
};

$.ajax({
  url: baseUrl+"chat.php",
  data: a,
  type: 'post',
  success: function(data) {
    alert(data);
  }
});

You may then access the data in your PHP script like this:

$_POST['test'];
$_POST['test2'];
Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way to do this in the style of an <input> element where the name field is test[] and the array indices are auto incremented?
@Kevin_TA, just use { test: ["array", "of", "values"] } as the data argument for $.ajax. It will get serialized to test[]=array&test[]=of&test[]=values.
"a" is an object, not an array in this example. Any ordering will be lost.
@sivann that's what the OP wanted. His a array is actually just an object.
@IonuțG.Stan it's not an object, it says new Array(). Now if that solution was ok with him that's another matter :-)
|
17

I used this:

var newArray = new Array();
newArray.push("item1");
newArray.push("item2");
newArray.push("item3");

$.ajax({  
    type: "POST",
    url: urlToPost,
    data: JSON.stringify(newArray),
    contentType: "application/json"
   });

Comments

6

I prefer doing it this way:

ie.

var data = [{ name: 'test1', value: 'test data' }, { name: 'test2', value: 'test data' }];

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

Server side (PHP): $_POST['test1']; $_POST['test2'];

Comments

3

Here is an example how I pass arrays (from real-life code) :

$.ajax({
  type: 'POST',
  url: url,
  data: { CartID : cartID, 'Manufacturers[]' : manufacturers, 'PartNumbers[]' : partNumbers },
  success: function(res)
  {
    ...
  },
  dataType: "json",
  async: false
});

then on the server-side:

$cartID = $_POST['CartID'];
$manufacturers = $_POST['Manufacturers'];
$partNumbers = $_POST['PartNumbers'];

Comments

1

Shortest version

$.post(url, { 'test[]': myArray });

Server side: $myArray = $_POST['test'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.