Skip to content Skip to sidebar Skip to footer

Javascript - Pass Object Via Post

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

Solution 1:

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));

Solution 2:

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}

Post a Comment for "Javascript - Pass Object Via Post"