how ajax js works code example
Example 1: js ajax
function _GET_REQUEST(url, response) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response(this.responseText);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function _POST_REQUEST(url, params, response) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
response(this.responseText);
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
_GET_REQUEST('http://someurl', (response) => {
});
_POST_REQUEST('http://someurl', 'paramx=y', (response) => {
});
Example 2: JS ajax
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));