0

I have a form on a page that is for the most part straight html. One part of the form generates a fairly complex multidimensional object using javascript. Normally if I had a variable that I wanted to put into the POST request I would append a <input type="hidden" /> to the form, however if I try this by serializing the object as json, the json query is littered with inverted commas which corrupt the html of the form.

ie

<input type="hidden" name="test" value="[{"fruit":"orange", "vege":"carrot"}, {"vehicle":"bike"}]"/>

is not valid html.

I guess it is possible to escape every character and stripslashes server-side though this seems incredibly messy. Visually there is no reason to insert the data into the html. I would rather a way to append to the POST data before the form is submitted using just javascript/jQuery.

This is trivial were I submitting the form with ajax, however for various reasons the form should forward to the processing page.

1 Answer 1

1

The simplest thing to do would be to use single quotes around the value attribute, and double quotes in the JSON:

<input type="hidden" name="test" value='[{"fruit":"orange", "vege":"carrot"},     {"vehicle":"bike"}]' />

Alternatively you could do the opposite:

<input type="hidden" name="test" value="[{'fruit':'orange', 'vege':'carrot'},     {'vehicle':'bike'}]" />

However, if you use the second approach on the server side you'd have to replace the single quotes with double quotes in order for it to be valid JSON.

Sign up to request clarification or add additional context in comments.

7 Comments

Yea I did try this as well, however server side the string comes in as [{\'fruit\':\'orange\', \'vege\':\'carrot\'}, {\'vehicle\':\'bike\'}]" for some reason. Browser escaping perhaps. But like I said, this is possible but it seems like a roundabout solution
Are you doing a basic form post? It's odd that escape characters are getting added automatically. What server side technology are you using? You could just write something to clean up the JSON before you use it.
You could try Url Encoding the JSON, which I think would solve the problem.
Server side is just Apache, PHP 5.2 - fairly standard. The form is submitted with a .submit() call from a query ui dialog button, but other than that it is pretty ordinary. Is there no jQuery magic that can mimic what a browser does when it posts a form?
Okay, so you're calling .submit() on the form? That should be fine. When is this JSON generated? On the server side, if so there should be a simple url encode function in PHP, if you could URL encode it in JS using the escape function.
|

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.