Explanation:
I am trying to POST/PUT the following text
{"email":"DD@GMAIL.COM"}
via xhttp.send to an external server. I need to post the double quotes with it, but how do I do that? I read about htmlentities, specialchars et cetera but I still, after an hour or more, can not find the solution. And of course, this would not work (because of the double quotes clash):
xhttp.send("{"email":"DD@GMAIL.COM"}");
This is the script until now:
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("PUT", "http://www.example.com/json", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader('X-CSRF-Token', "csrf_token");
xhttp.send("fname=Henry"); //TODO: MAKE SURE THAT EXACTLY {"email":"DD@GMAIL.COM"} WILL BE 'POSTED'.
}
</script>
</body>
</html>
Please help me, I can not figure this out.
You can wrap the string in single quotes
xhttp.send('{"email":"DD@GMAIL.COM"}');
However, it's best to serialize it to a string from an object
xhttp.send(JSON.stringify({ email :"DD@GMAIL.COM"}));
Also you should send the correct content-type header
xhttp.setRequestHeader("Content-Type", "application/json");