Javascript - XMLHttpRequest - A simple POST example

By convention, we name the XMLHttpRequest variable xhr.

 
var data = {
    username: "test",
    password: "12345"
};
 
var json = JSON.stringify(data);
console.log(json);
 
var xhr = new XMLHttpRequest();
xhr.open("POST", "/articles/javascript-xmlhttprequest-a-simple-post-example/update.aspx");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
 
xhr.onreadystatechange = function () {
    console.log("readyState = " + this.readyState + ", status = " + this.status);
    if (this.readyState == 4 && this.status == 200) {
        var result = this.responseText;
        console.log(result);
    }
};
 
xhr.send(json);
 


Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath