2

I have a multidimensional array I am trying to pass in as data through a jQuery ajax call to my PHP script.

I declared lobby_state with the following code:

lobby_state = [];
lobby_state.users = 3;
lobby_state.user = [];
lobby_state.user[0].username = 'john';
lobby_state.user[0].age = 30;
lobby_state.user[0].sex = 'M';
lobby_state.user[1].username = 'kim';
lobby_state.user[1].age = 17;
lobby_state.user[1].sex = 'F';
lobby_state.user[2].username = 'mary';
lobby_state.user[2].age = 51;
lobby_state.user[2].sex = 'F';

I'm passing in a total of 2 values, a simple string, and the multidimensional array:

$.ajax({
    type: "POST",
    url: "app/lobby/lobby-process.php",
    data: {  
        'action': 'update',
        'state': lobby_state
    },
    dataType: "json",
    success: function(data){
...

When I execute this, it seems to completely ignore the lobby_state value, and it only passes in the 'action' value, as shown in the Chrome developer console request values below.

enter image description here

I tried following all the examples of passing in arrays but nothing seems to work. Am I missing something?

1
  • Please do a console.log of the array and paste here! Commented Nov 19, 2014 at 6:54

1 Answer 1

3

You need to pass it as a JSON string:

state: JSON.stringify(lobby_state)

An example on how to declare an array properly:

var lobby_state = [],
    john = { username: 'john', age: 30, sex: 'M' };

lobby_state.push(john);

console.log(lobby_state);

You could add the object to the array directly as well:

var lobby_state = [{ username: 'john', age: 30, sex: 'M' }];

http://jsfiddle.net/p8x14goy/1/

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks filur, one step closer! However, when I make that change, it seems to convert lobby_state into an empty json value of '[]'.
@user3130810 The problem is that lobby_state.user[0] is undefined. Let me update with an example on how to declare the array properly
What if I also want to add a user count like in my original post? I think that is what's causing the issues at the moment. I was hoping I could keep it all under the same variable, so lobby_state would contain a single integer, as well as an array.
@user3130810 You don't need a property for it. Just look at the size of the array

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.