1

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(??);
}
Rob
  • 14,746
  • 28
  • 47
  • 65
Lithicas
  • 3,793
  • 7
  • 23
  • 32

2 Answers2

2

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);
0
function postRequest(theUrl)
{
          var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
          xmlhttp.open("POST", "enter your url");
          xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
          xmlhttp.send(JSON.stringify({name:"example name", surname:"data"}));
       return xmlHttp.responseText;
}
ahankendi
  • 244
  • 3
  • 9