Jeremy Troy Suchanski

Web Frontend Development II

Gary James

May 2, 2022

L05 Readings Notes

Ch13: AJAX (Notes)

Asynchronous: By using callbacks the program doesn’t have to stop and wait for the response when a request for data is sent. It can carry on while waiting for an event that will fire when a response is received.

JavaScript: (originally designed as a client-side scripting language, which added dynamic features to the web page that was returned from the server.) Ajax allows JavaScript to request resources (usually JSON data or small fragments of text or HTML) from a server on behalf of the client.

XML: documents were often used to return data when the term Ajax was originally coined. Currently you must use DOM methods to parse XML files because it is not natively supported in JavaScript.

JSON: is currently the most commonly used in Ajax. It is more lightweight and easier to parse than XML because it is natively supported in JavaScript, so you can deal with JavaScript objects instead of using DOM methods to parse it. The term Ajaj is sometimes used to describe the technique.

fetch(): a global method that only has the mandatory argument of the URL of the resource you wish to fetch. Code Example:

  1. fetch('https://example.com/data')
  2. .then( // code that handles the response )
  3. .catch( // code that runs if the server returns an error )

ok property: checks to see if the response is successful & will return true if the status property is between 200 and 299.

status property: is based on the HTTP status code. Usually:

  1. 200: the response was successful
  2. 201: if a resource was created
  3. 204: when the request is successful but no content is returned
  4. Rejected: the promise will only be rejected in the case of a network error (creating the need to manually check for other failures)
  5. Manual check: use an if block to check if the request was successful, and throw an error otherwise. Code Example

const url = 'https:example.com/data';

 

fetch(url)

.then((response=> {

    if(response.ok) {

        return response;

    }

    throw Error(response.statusText);

})

.thenresponse => // do something with response )

.catcherror => console.log('There was an error!') )

statusText property: specifies the status message that corresponds to the code returned

headers – headers object that contains any headers associated with the response

url – a string containing the URL of response

redirected – A boolean value specifying if the response is the result of a redirect

type – A string value of 'basic', 'cors', 'error' or 'opaque'.

  1. basic:  is used for a response from the same domain. 
  2. cors: the data was received from a valid CORS request from a different domain.
  3. opaque: a response received from 'no-cors' request from another domain, which means access to the data will be severely restricted. 
  4. error: a network error occurs.

redirect(): used to redirect to another URL. At the present time, there is no support for the redirect() method in any browser.

text(): takes a stream of text from the response, reads it to completion and then returns a promise that resolves to a USVSting object that can be treated as a string in JavaScript.

Code Example

fetch(url)

.thenresponse => response.text() ); // transforms the text stream into a JavaScript string

.thentext => console.log(text) )

.catcherror => console.log('There was an error: 'error))

blob(): used to read a file of raw data, such as an image or a spreadsheet. Once it has read the whole file, it returns a promise that resolves with a blob object. Code Example

fetch(url)

.thenresponse => response.blob() ); // transforms the data into a blob object

.thenblob => console.log(blob.type) )

.catcherror => console.log('There was an error: 'error))

json(): used to deal with these by transforming a stream of JSON data into a promise that resolves to a JavaScript object. Code Example (the Object.entries() method is used to view the key and value pairs in the returned object.):

fetch(url)

.thenresponse => response.json() ); // transforms the JSON data into a JavaScript object

.thendata => console.log(Object.entries(data)) )

.catcherror => console.log('There was an error: 'error))

const response = new Response'Hello!', {

    ok: true,

    status: 200,

    statusText: 'OK',

    type: 'cors',

    url: '/api'

});

url: the URL of the requested resource (the only property that is required).

method: a string that specifies which HTTP method should be used for the request. By default, this is 'GET'.

headers: is a Headers object that provides details of the request's headers.

mode: allows you to specify if CORS is used or not. CORS is enabled by default.

cache: allows you to specify how the request will use the browser's cache. For example, you can force it to request a resource and update the cache with the result, or you can force it to only look in the cache for the resource.

credentials: lets you specify if cookies should be allowed with the request.

redirect: specifies what to do if the response returns a redirect. There’s a choice of three values: 'follow' (the redirect is followed), 'error' (an error is thrown) or 'manual' (the user has to click on a link to follow the redirect).

GET requests: to retrieve resources

POST requests: usually used to create a resource but can actually perform any task

PUT requests: to upsert, which means insert a resource or update it entirely

PATCH requests: to make partial updates to a resource

DELETE requests: to delete a resources

const request = new Request('https://example.com/data', {

    method: 'GET',

    mode: 'cors',

    redirect: 'follow',

    cache: 'no-cache'

});

const headers; 

headers = new Headers({ 'Content-Type''text/plain''Accept-Charset' : 'utf-8''Accept-Encoding':'gzip,deflate' })

has(): used to check if the headers object contains the header provided as an argument. (i.e. headers.has('Content-Type');)

get(): returns the value of the header in the argument (i.e. headers.get('Content-Type');)

set(): used to set a value of an already existing header, or create a new header with the value provided as an argument if it does not already exist. (i.e. headers.set('Content-Type', 'application/json');)

append(): adds a new header to the headers object. (i.e headers.append('Accept-Encoding','gzip,deflate');)

delete() – Removes the header provided as an argument. (i.e. headers.delete('Accept-Encoding');)

keys(), values() and entries(): Iterators that can be used to iterate over the headers key, values or entries (key and value pairs). (i.e. for(const entry of headers.entries(){

console.log(entry);})

const form = document.forms['todo'];

form.addEventListener('submit'addTaskfalse);

 

function addTask(event) {

    event.preventDefault();

    const number = form.task.value;

    const task = {

        userId: 1,

        title: form.task.value,

        completed: false

    }

    const data = JSON.stringify(task);

    const url = 'https://jsonplaceholder.typicode.com/todos';

 

    const headers = new Headers({

        'Accept''application/json',

        'Content-Type''application/json'

    });

    const request = new Request(url,

    {

        method: 'POST',

        header: headers,

        body: data

    })

 

    fetch(request)

    .thenresponse => response.json() )

    .thentask => console.log(`Task saved with an id of ${task.id}`) )

    .catcherror => console.log('There was an error:'error)) }

action attribute: most forms have this; it specifies the URL to use if the form is sent without using Ajax.

method attribute: will specify the HTTP verb to use.

const request = new Request(form.action, {   

        method: form.method,

        header: headers,

        body: data  })

const form = document.forms['todo'];

 

form.addEventListener('submit'addTaskfalse);

 

function addTask(event) {

    event.preventDefault();

    const task = new FormData(form);

    const url = `http://echo.jsontest.com/id/1/title/${form.task.value}`;

    const headers = new Headers({

        'Accept''application/json',

        'Content-Type''application/json'

    });

    const request = new Request(url,

    {

        method: 'POST',

        mode: 'cors',

        header: headers,

        body: JSON.stringify(task) })

 

    fetch(request)

    .thenresponse => response.json() )

    .thendata => console.log(`${data.title} saved with an id of ${data.id}`) )

    .catcherror => console.log('There was an error:'error))

}

append() method: use to add data to the form data instance as key-value pairs Code Ex:

data = new FormData(); // argument of no form creates an empty form data instance

data.append('height'75);

A Living Standard: (Fetch API) the specification is being developed 'in the wild', meaning it’s still subject to change as developers, browser vendors and end-users provide feedback about how it works. Living standards often stay relatively stable, especially once they are implemented in browser engines. By using it you are helping to develop future standards. (jQuery library has the generic ajax() method like the fetch() method.)