Lithicas Lithicas - 9 days ago 7
Javascript Question

Convert input element to JSON and send to REST service

I'm trying to convert a HTML input element and the text within to a JSON object and then send it to a REST service.

How do I go about doing this using vanilla JS, not JQuery or any other libs. I have no clue what to put inside http.send() to send the text inside the input field.

HTML

<input id="answer" name="message" type="text" onclick="sendAnswer()" />


JS

function sendAnswer() {
http.open("POST", nextUrl, true);
http.setRequestHeader("Content-type", "application/json");

http.send(??);
}

Answer

If you're sending a post request, you put the JSON data for your request body inside the https.send()

something like:

var data = JSON.stringify({"email":"email@email.com","name":"Bob"});
http.send(data);