nitte93user3232918 nitte93user3232918 - 5 months ago 35
Javascript Question

Javascript & inside a string

I have an input field which accepts college name, and some other input fields for other usage.

1)Next, I'm creating a JSON structure with all these inputs and

2)Doing JSON.Stringify(JSONdata) for this Json data.

3)Setting the XHR content-type header to:

xhr.setRequestHeader("Content-Type", "application/X-www-form-urlencoded");

calling a post request to server with this stringified input.

There everything works fine, except for this one particular college input>
Which looks something like this:

St. Joseph's College of Arts & Science, Cityname.

After parsing the data at serverside, I'm expecting my string at server to look something like this:

"college":"St. Joseph\'s College of Arts & Science, Cityname",

Instead it is looking

"college":"St. Joseph\'s College of Arts ',' Science, Bangalore",

is getting replaced by a

And thus it is throwing me error:

: Unexpected end of JSON input<br> &nbsp; &nbsp;at Object.parse (native)<br> &nbsp; &nbsp;at server.js:206:28<br> &nbsp; &nbsp;at Layer.handle [as handle_request]

I want it accept all the input field no matter what's inside it.

requestObject is my Json data.

var data = "Data="+JSON.stringify(requestObject);
xhr.setRequestHeader("Content-Type", "application/X-www-form-urlencoded");


You just need to URI-encode the string you're sending, just like any other time you're sending strings via URI-encoded form data that you're manually creating:

var data = "Data="+encodeURIComponent(JSON.stringify(requestObject));
// ----------------^^^^^^^^^^^^^^^^^^^----------------------------^
xhr.setRequestHeader("Content-Type", "application/X-www-form-urlencoded");

& is special in URI-encoding (as are several other characters). encodeURIComponent ensures those are properly encoded for transmission and decoding at the other end. Once decoded, you'd then use whatever JSON parser you use in your environment to turn the JSON (a string) into an object structure.