Ajax request in es6 vanilla javascript

29,071

Solution 1

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 async, it is impossible. But you can make it look like not async operation with Async-Await feature.

Solution 2

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

}

Solution 3

Nowadays you don't need to use jQuery or any API. It's as simple as doing this:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState === 4 && this.status === 200) {
    console.log(this.responseText);
  }
};
xmlhttp.open('GET', 'https://www.example.com');
xmlhttp.send();
Share:
29,071
sacora
Author by

sacora

Updated on July 09, 2022

Comments

  • sacora
    sacora almost 2 years

    I am able to make an ajax request using jquery and es5 but I want to transition me code so that its vanilla and uses es6. How would this request change. (Note: I am querying Wikipedia's api).

          var link = "https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids="+ page +"&format=json&callback=?";
    
        $.ajax({
          type: "GET",
          url: link,
          contentType: "application/json; charset=utf-8",
          async: false,
          dataType: "json",
          success:function(re){
        },
          error:function(u){
            console.log("u")
            alert("sorry, there are no results for your search")
        }