Fetch/Promise

'fetch()' is the new way to do an 'AJAX' call. 'fetch' returns a 'Promise' which many think is a much better way to handle async events than with 'callbacks'. 'fetch' can do both 'GET' and 'POST' functions as well as any other HTTP command. To use 'fetch' you would do a call with two argments: the URL and an optional option argument. 'fetch' returns a 'Promise' which resolves to a 'response' object.

fetch(url, opt)
.then(resp => {
  // The 'response' object contains a 'body' object which can be parsed as 'json' or 'text'
  return resp.json();
})
.then(data => {
  // The result of the 'json' or 'text' method is the data.
  console.log(data);
});

To do a 'POST' you would fill in the 'opt' argments:

const opt = {
  body: "arg1=one&arg2=two", // This can also be passed as json date
  method: "POST",
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
    // 'content-type': 'applicatin/json' // if you pass json data
    // Note that your application on the server can return any kind of data it wants (text or json
    // or xml etc).
  }
};

Example


fetch-promise.php


query.ajax.php


uptest.php