JavaScript Tutorial
indexjavascript history javascript versions environment setup variables and data typesOperatorsstrings and numbers programming constructs arrays built in objects functions objects call apply bind closures error handling debugging CallbacksJS in Browser
BOM and DOMBrowser EventsWeb APIAjaxJQueryMost popular librariesAdvanced
prototypes Object Oriented ProgrammingModulesAsynchronous programmingBinary DataInternationalizationreactangularjsProjectsMiscellaneous
typescriptJS ecosystemChrome dev toolstesting frameworksInterview questions and AnswersAjax tutorial
Ajax stands for asynchronous javascript and xml. Normally you will need to refresh the entire page to get fresh data from server. But with Ajax, you can send and recieve the data to and from server without refreshing the full page. There are 3 ways in which you can make ajax call.- XMLHttpRequest
- fetch API
- axios API
XMLHttpRequest
Below example demonstrates how to make ajax call using XMLHttpRequest.
function getServerData() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
//If json response, parse it
//var jsonObject = JSON.parse(this.responseText);
//If xml response, use responseXML prop
//alert(this.responseXML);
}
};
xhttp.open("GET", "/abc.html");
xhttp.send();
}
We can also send headers in request. For more information, visit XMLHttpRequest Object fetch API
fetch API is a modern API based on promises. It is supported in all modern browsers.
let url = '/mydata';
let options = {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
name: "Sagar",
postcode: 3020
})
};
let response = await fetch(url, options);
if (response && response.ok) {
response.headers.forEach(function (val, key) {
console.log(key + " -> " + val);
});
let jsonObject = await response.json();
//process json Object
}
axios API
axios is also based on promises but here are some main differences between fetch and axios.- fetch is a built-in api in all browsers. To use axios api, you will need to install it first.
- fetch request's body property is equivalent to Axios request's data property
- fetch body needs to be converted into string but in axios, you can send JSON object directly.
- In fetch function, we can pass the url to be fetched. In axios, we have to pass the url via options object
- In fetch api, To convert, response to json object, you need to use json() method on response object. But in axios, you can directly access json object using data property.
- fetch and axios uses promises but xmlhttprequest uses callbacks
let url = '/mydata';
let options = {
method: 'POST',
url: url,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
data: {
name: "Sagar",
postcode: 3020
}
};
let response = await axios(options);
//response.headers
if (response && response.status === 200 && response.statusText === 'OK') {
let jsonObject = await response.data;
// process jsonObject here
}
Web development and Automation testing
solutions delivered!!