Sending a POST request in Simple Javascript

So recently i wanted to send a POST request to one of my backends using only simple plain Javascript. Found this code on Quora which worked nicely.


Code :

  1. xhr = new XMLHttpRequest();
  2. var url = "url";
  3. xhr.open("POST", url, true);
  4. xhr.setRequestHeader("Content-type", "application/json");
  5. xhr.onreadystatechange = function () {
  6. if (xhr.readyState == 4 && xhr.status == 200) {
  7. var json = JSON.parse(xhr.responseText);
  8. console.log(json.email + ", " + json.name)
  9. }
  10. }
  11. var data = JSON.stringify({"email":"tomb@raider.com","name":"LaraCroft"});
  12. xhr.send(data);

Comments

Popular posts from this blog

Wasted about an hour of my life on something so trivial

Connecting to AWS DynamoDb with .NET CORE

Hiding YouTube comments section