AJAX Javascript Fetch Code Examples

Javascript fetch, wraps around XMLHttpRequest request uses promises to make it simpler to code

Overview

    Overview

  • The Fetch API allows you to asynchronously request for a resource.
  • Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json(). These methods also resolve into the actual data.
  • Use the status and statusText properties of the Response object to get the status and status text of the response.
  • use the catch() method or try...catch statement to handle a failure request.

Overview

  Main paramaters 
Fetch(url,[options])
fetch(url, {
    method: 'POST',     
    headers: {
        'Content-Type': 'application/json' 
        'Accept'      : 'application/json'  
    },     
    body: JSON.stringify(data) // body data type must match 
	           "Content-Type" header
    }).then(function (response) {
             return response.json();
    })
    .then(function (data) {	
	    //process data in json form here	
	 }

Details

Method Html mode, one of POST, Get etc
headers restricted access to html header
body
Mode used for cors access see cors
cache used for cors access see cors

response body converts return to json, text ect

Basic examples

basic

fetch('https://api.github.com/users/dummy') 
  .then(response => response.json())  // convert to json
  .then(json => console.log(json))    // print data to console
  .catch(err => console.log('Request Failed', err)); 
					
Send GET params using urlstring
fetch('http://www.hyperaccess-dev.co.uk/AJAX/db-debug-get.php?table=Snippets') 
  .then(response => response.json())  // convert to json
  .then(json => console.log(json))    // print data to console
  .catch(err => console.log('Request Failed', err)); 
					
Send POST params using FormsData
The FormData object lets you compile a set of key/value pairs to send. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.
var formData = new FormData();
formData.append('status', 'Open');	
formData.append('type', 'Read');
formData.append('file', 'read.txt');
then
  fetch(url, { method: 'POST', body: formData }) ...
Send params via JSON Array
build json array then in Body convert array to string
data_array = {"type":"select_images"  , 
		"path":"../Images/gardening/newplants", "selid": "sel"};
const options = { method: 'POST', body:  
       JSON.stringify(data_array) } ;
  
fetch("foldersdir.php", options)
      .then((response) => {return response.text();})
      .then((data) => {$("#imagelist").html(data) ;
      }); 
					
Error Reporting
Fetch() rejects only if a request cannot be made or a response cannot be retrieved. It might happen because of network problems: no internet connection, host not found, the server is not responding. The ok property lets you separate good from bad HTTP response statuses.
	 textfile = "file1xxx.txt" ;
     fetch(textfile)
       .then(response => {
            if (!response.ok) {
			    alert ("failed to display " + textfile + " due to " + response.status);
                //throw new Error("HTTP error " + response.status);
				return ("failed to load " + textfile + " with " + response.status);
            }
            return response.text();
       })		
					
Fetch with async/await
					
Parallel fetch requests
					


						   


						   

Javascript Error Handing


						   

Advance usages

Http header

Each time a user website or webpage in a browser, an HTTP request header is generated by the browser and is sent to the website / Web server. Typically, the information within the HTTP request header is in form of plain text record of data/page request made by the user. It can include be used to control security CORS, define data to be passed to server, caching etc the Fetch header enable you to set theses values, Normally they can be inoged, however if access a 3rd party web service you may have to set values as requried.

http Response object

The information, in the form of a text record, that a Web server sends back to a client's browser (with the requested data) in response to receiving an HTTP request. includes the destination IP address, data type, host address and more.


						   


						   

Actual code used on this page


						   

CORS - fetch from 3rd party sites

Fetch Code CORs

Result : cors explained

Display Code (php-file-read-json.php) :

Other addions

Await - the asynchronous function is paused until the request completes.

Read More Read More