Ajax request in es6 vanilla javascript
Probably, you will use fetch API:
fetch(link, { headers: { "Content-Type": "application/json; charset=utf-8" }})
.then(res => res.json()) // parse response as JSON (can be res.text() for plain response)
.then(response => {
// here you do what you want with response
})
.catch(err => {
console.log("u")
alert("sorry, there are no results for your search")
});
If you want to make not async, it is impossible. But you can make it look like not async operation with Async-Await feature.
AJAX requests are useful to send data asynchronously, get response, check it and apply to current web-page via updating its content.
function ajaxRequest()
{
var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";
var xmlHttp = new XMLHttpRequest(); // creates 'ajax' object
xmlHttp.onreadystatechange = function() //monitors and waits for response from the server
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //checks if response was with status -> "OK"
{
var re = JSON.parse(xmlHttp.responseText); //gets data and parses it, in this case we know that data type is JSON.
if(re["Status"] === "Success")
{//doSomething}
else
{
//doSomething
}
}
}
xmlHttp.open("GET", link); //set method and address
xmlHttp.send(); //send data
}