Wayne
Wayne

Reputation: 1290

Submitting a Javascript object to PHP

A newbie question from me, please.

I have a large data set that I prefer to be submitted as an object instead of an array; e.g.

foo = bar = baz = {};
$.ajax({
    url: "index",
    type: "post",
    data: { foo: foo, bar: bar, baz: baz },
    dataType: "json"
});

Upon submit, Firebug tells me that I have submitted:

bar [object Object]
baz [object Object]
foo [object Object]

What I want is to be able to access the contents of foo, bar, baz (contrived example, of course).

Is this possible in Javascript? Or do I need to use arrays, which I do not prefer?

Upvotes: 0

Views: 2315

Answers (2)

artlung
artlung

Reputation: 33833

bar, baz, and foo in your example are empty objects, the [object] nonsense is JavaScript doing its best to turn the variables into strings. I suggest including something that will turn your objects into JSON strings. See json.org and specifically json2.js and then call the stringify() method on each of them:

foo = bar = baz = {};
$.ajax({
    url: "index",
    type: "post",
    data: { foo: foo.stringify(), bar: bar.stringify(), baz: baz.stringify() },
    dataType: "json"
});

Upvotes: 3

krosenvold
krosenvold

Reputation: 77201

No. Everything that is submitted via HTTP is basically a string or an array of strings. You can use JSON to convert each object into a string representation, which may be what you want.

Upvotes: 2

Related Questions