Send data to the server using Ajax using JavaScript Promises

6

Since the Javascript Promises promise a lot. One of the things that I would like to know is how to make an Ajax request with promises , in pure Javascript, without having to go through third-party libraries.

It would be a request that adequately addresses the success or failure of the request made, indicating the result obtained or an error message.

    
asked by A. Cedano 14.07.2017 в 15:23
source

2 answers

4

The new API Fetch allows you to make "AJAX" calls ( Request ) and implements Promises by default.

Example of use:

function get(method) {
  var url = document.getElementById("datos").value;

  fetch(url, {
    method: method
  }).then(function(response) {
    response.json().then(function(object) {
      console.log("¡Correcto!", object);
    });
  }).catch(function(error) {
    console.error("!Hubo un error!", error);
  });
}
Introduzca URL de un servicio REST y pulse Enviar:<br />
<input id="datos" type="text" value="https://api.github.com" size="33" />
<input type="button" onclick="get('GET')" value="Enviar..." />

More info:

* David Walsh - fech API
* Google Developers - Introduction to fetch ()
* Github - fetch polyfill

    
answered by 14.07.2017 / 16:23
source
3

This would be an example of a call function to Ajax, using Promises.

With our function myAjax() we can make requests via ajax and get the answer, or the error code, transparently, without the need for libraries like jQuery.

As indicated in the link below:

  

The previous APIs will be updated to use promises and, if possible,   it will be done so that they are compatible with previous versions.   XMLHttpRequest is a great candidate.

Which means that calls to Ajax through Promises will be much easier in the future. While that arrives, we can use a function like this, passing to the function in parameter the method ( GET, POST ) and the url of the REST service, API, or a php, json or other of our applications.

function myAjax(method, url) {
  // Devolver una nueva Promise.
  return new Promise(function(resolve, reject) {
    // Hacer lo usual de XHR 
    var req = new XMLHttpRequest();
    req.open(method, url);

    req.onload = function() {
      // Esto es llamado incluso cuando ocurre error 404 etc
      // Verificar el status
      if (req.status == 200) {
        // Resolver la Promise con el texto de respuesta
        resolve(req.response);
        console.log(req.response);
      } else {
        // De lo contrario, rechazar con el texto del estatus
        reject(Error(req.statusText));
      }
    };

    // Manejar errores de red
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Hacer la petición
    req.send();
  });
}

function get(method) {
  var url = document.getElementById("datos").value;
  myAjax(method, url).then(function(response) {
    console.log("¡Correcto!", response);
  }, function(error) {
    console.error("!Hubo un error!", error);
  })
}
Introduzca URL de un servicio REST y pulse Enviar:<br />
<input id="datos" type="text" value="https://api.github.com" size="33" />
<input type="button" onclick="get('GET')" value="Enviar..." />

Links

answered by 14.07.2017 в 15:23