Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax request in es6 vanilla javascript

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")
    }
like image 816
sacora Avatar asked Dec 20 '17 13:12

sacora


People also ask

Can AJAX be used with JavaScript?

AJAX just uses a combination of: A browser built-in XMLHttpRequest object (to request data from a web server) JavaScript and HTML DOM (to display or use the data)

Are AJAX requests HTTP requests?

Ajax. Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method.


1 Answers

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.

like image 96
termosa Avatar answered Oct 05 '22 07:10

termosa