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:
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:
const url = 'https:example.com/data';
fetch(url)
.then((response) => {
if(response.ok) {
return response;
}
throw Error(response.statusText);
})
.then( response => // do something with response )
.catch( error => 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'.
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)
.then( response => response.text() ); // transforms the text stream into a JavaScript string
.then( text => console.log(text) )
.catch( error => 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)
.then( response => response.blob() ); // transforms the data into a blob object
.then( blob => console.log(blob.type) )
.catch( error => 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)
.then( response => response.json() ); // transforms the JSON data into a JavaScript object
.then( data => console.log(Object.entries(data)) )
.catch( error => 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', addTask, false);
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)
.then( response => response.json() )
.then( task => console.log(`Task saved with an id of ${task.id}`) )
.catch( error => 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', addTask, false);
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)
.then( response => response.json() )
.then( data => console.log(`${data.title} saved with an id of ${data.id}`) )
.catch( error => 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.)