Reputation: 7866
I want to send a json formatted string as a hidden field for a form.
I get the data as follows:
$.getJSON(email_url,function(fb){
var pic_url = "http://graph.facebook.com/"+fb.id+"/picture";
json_details.push({name: fb.name, fbuid: fb.id, picUrl: pic_url, birthday: fb.birthday });
var manager_details = JSON.parse(json_details);
html += "<form id='new_celebration"+fb.id+"' method='post' action='/celebrations' accept-charset='UTF-8'>";
html += "<input type='hidden' id='manager' value='"+manager_details +"' name='celebration[manager_details]' />"
html += "</form>";
$('.facebookfeed').html(html);
});
But if I add it this way I get extra "\".
How can I add the json object to the request string so I can send this data in with the form?
Upvotes: 1
Views: 937
Reputation: 8055
You could also base64 encode the stringified json_details object.
That way you're sure it won't have any problems when being sent to the server .
Edit
Have a look at : http://developers.facebook.com/docs/authentication/signed_request/
And for encoding in js just use google : http://www.webtoolkit.info/javascript-base64.html this is the first hit.
Upvotes: 0
Reputation: 39395
I believe that you'll want to do this:
manager_details = escape(JSON.stringify(json_details));
...
html += "<input type='hidden' id='manager' value='"+manager_details +"' name='celebration[manager_details]' />"
JSON.stringify converts your JSON object to string. escape() sets up your value to be sent as a URL parameter, which is what will happen since your form content-type is not set to multipart/form-data; this will also remove the '\' that you're referring to.
Upvotes: 1
Reputation: 2734
I think you want JSON.stringify, not parse.
If I could zoom out a bit for a couple of suggestions, though:
Why not have the form elements already existing on your page, and do something like $('#manager').val(manager_details);
instead of generating the HTML in JS? In general, it's good practice to avoid creating HTML strings in your JS if possible (separation of concerns and all that)
If you're already using JS, why not skip the hidden field entirely and simply attach the data on form submission? Meaning, you already have your data in manager_details
, so on from submit
, do a $.post()
and include manager_details
in your data.
Upvotes: 1