Marc Baumann
Marc Baumann

Reputation: 77

Pass PHP array through xhr request

I'm wondering how I can pass a PHP form array through a XHR request. I'm building an RESTful API for processing Symfony2 forms. Some form elements have to be filled in with creepy data like:

foo_form[bar][] = 1
foo_form[bar][] = 2

My question is, how I can send this through a XHR request in a JS library.

var client = FooHttpClient(options);

var data = {
    'foo_form[bar][]' : 1,
    'foo_form[bar][]' : 2
};

client.send(data);

The problem here is, that the first data value (foo_form[bar][] = 1) will be overriden by the second value.

Has anyone a solution for this?

Greetings,

--Marc

Upvotes: 2

Views: 747

Answers (4)

dev-null-dweller
dev-null-dweller

Reputation: 29492

Since data passed to send will be transformed to urlencoded POST data, try using JavaScript object structure:

var data = {
    "foo_form": {
        "bar": [1,2]
    }
};

If the API does not handle multiple levels of object/arrays, you can still use your attempt, but add numerical indexes to an array:

var data = {
    'foo_form[bar][0]' : 1,
    'foo_form[bar][1]' : 2
};

Upvotes: 0

Spudley
Spudley

Reputation: 168853

PHP provides the json_encode() function specifically for this.

json_encode() converts a PHP array or object structure into a JSON string. JSON is a serialised data format which is directly compatible with Javascript (JSON stands for Javascript Object Notation).

Once the JSON string is in your Javascript code, you can decode it using JSON.parse() to convert it into a JS object. (note, older browsers - eg IE6 - do not support this, so you may need to use a library to parse it (it is possible that your FooHttpClient provides this functionality built-in; we don't know enough about FooHttpClient from the question to help you with that though).

PHP also has a json_decode() function to convert a valid JSON string back into a PHP array, so you can also send JSON data back from JS to your PHP program.

Virtually all languages have JSON encode/decode functionality, so JSON is a good data format for cross-language communication.

Upvotes: 1

Pankaj Sharma
Pankaj Sharma

Reputation: 1853

var data = [
{'foo_form[bar][]' : 1},
{'foo_form[bar][]' : 2}
];   //array of json objects

Upvotes: 0

btm1
btm1

Reputation: 3856

Join the array and turn it into a comma separated list where you can then pass it as a URL param. Then use GET on the other side and explode the list back into an array.

Upvotes: 0

Related Questions