14

I have an object that looks like this

var obj = { p1 : true, p2 : true, p3 : false }

I am looking to try and pass this object as part of a post request.

however on the other end (in php) all I get is

[object Object]

How can I send an object via post?

basically what I am trying to do is

I have an input that is hidden and is created like so

<input id="obj" type="hidden" name="obj[]">

which is part of a hidden form.

when a button is pressed I have

$(#obj).val(obj);
$('form').submit();


Please no suggestions to use ajax as I must do it this way as it is to download a dynamically created file.

2 Answers 2

28

You need to serialize/convert the object to a string before submitting it. You can use jQuery.param() for this.

$('#obj').val(jQuery.param(obj));
Sign up to request clarification or add additional context in comments.

2 Comments

A+ first one to read the whole question, and your answer works perfect too :) Will accept asap
even works recursively {a: {b: 'c', d: {e: 'f', g: 'h'}, i: 'j'} => a[b]=c&a[d][e]=f&a[d][g]=h&i=j
14

You might consider using JSON notation to send the object to the server. If you include a JSON parser/renderer in your page, (it's built in on all modern browsers now, and also IE8 in standards mode) you can convert the object into a string preserving its full object graph. Most server-side languages now have JSON parsing available for them (in PHP it's json_decode, for instance). You can put that string in your hidden form field before sending the form.

That would look like this:

$('#obj').val(JSON.stringify(obj));
$('form').submit();

...and your server-side would see a string in the form

{ "p1" : true, "p2" : true, "p3" : false }

8 Comments

Please read the whole question. The form is needed as it is downloading a dynamically generated file, You cannot cause a file download from ajax data. I cannot store the file that is created anywhere either so, generating the file via the ajax call and returning a url will not work either.
@Hailwood: Can't believe I missed that. Fixed.
@T.J. Cheers, Your new answer will work. However i am using @Matt's answer :) (ps, you get an upvote from me)
@Hailwood: Glad Matt's solution will work for you, it's all about having options. :-)
Exactly, Actually I do prefer this option, but I am including jquery already, unless it has a built in JSON parser I dont really want to include another library. Most browsers now have a JSON parser already, but... IE6...
|

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.