AJAX and JSON
F28WP Web Programming
2020-2021
## Overview * What is **AJAX** and **JSON?** * How do we use AJAX? * **Syntax** and formatting * AJAX methods and properties * **Examples** * Questions and Discussion
## Revision Question What is the result? ``` (true + true) > 1 + false ``` * A. true * B. false * C. TypeError * D. NaN
## Answer Answer: **A.** true
---- (true + true) = 2, 1 + false = 1
## Revision Question What is the output for the following JavaScript? ``` function foo( a ) { a = [5,6]; } let b = [3,4]; foo( b ); console.log( b[1] ); ``` * A. 5 * B. 6 * C. 3 * D. 4
## Answer Answer: **D.** 4
## JSON * **JSON = JavaScript Object Notation** * JSON is a subsection of JavaScript (ECMA-262) * Language **independent** * Text-base (**human** readable) * Light-weight * Easy to use and parse
## JSON is **Not** * JSON is not a document format * JSON is not a markup language - **JSON is not XML** * JSON is not a general serilzation format - No recursive /recurring structures - No invisible structures - No function
## What do we use JSON objects for?
## What do we use JSON objects for? * JSON objects are used to **transfer data** between the server and the client * JSON is a **simple**, common representation of data
## Versions and Encoding * JSON has **no version** and no revision * JSON is very **stable** * Character Encoding is **Strictly** UNICODE
## JSON Data Types and Values * Strings * Numbers * Booleans * Objects * Arrays * null, true, false
## JSON **Objects** * Objects are *unordered* containers of key/value pairs * Objects are wrapped in **{ }** * Comma **,** separates key/value pairs * Colon **:** separates keys and values * Keys are strings * Values are from JSON data types * Also refereed to as (in other languages) : - struct, record, hashtable, associative array, ...
## Object ``` { "name": "Jack", "at" : true, "grade": "A", "format": { "type": "rect", "width": 2220, "framerate": 24 } } ```
## JSON **Array** * Arrays are *ordered* sequences of values * Vales can be of different types * Arrays are wrapped in **[]** * Comma **,** separate values * Implementation can start at index 0 or 1
## JSON Array Example ``` { "vals": [ "Bob", "Tom", 22 ] } ```
## Examples Object with two member ``` { "course": "6.69", "cname" : "aaa", } ``` Array with 3 elements ``` ['aa', 'bbb', 'cccc'] ``` Object with an array as a value ``` { "course": "abc", "times": ["2", "3", "4"] } ```
## Examples Key-value pairs ``` var test = { "fname": "Bob", "lname": "Tom", "age": 22 }; ``` Accessing the JSON objects: ``` document.writeln("FName: " + test.fname); document.writeln("LName: " + test.lname); document.writeln("Age : " + test.age ); ```
## Examples Objects with **objects** and **array** ``` var a = { "john": { "label": "jjj", "data": [[ 22, 233], [22,33]] }, "james": { "label": "bbbb", "data": [[ 12, 33], [99,33]] } } ``` To acces the data, we could do: ``` a.john.data[0][0] ``` Value: 22
## JavaScript and JSON ```JSON.stringify()``` * Takes a Javascript object and produces a **JSON string** from it ```JSON.parse() ``` * Takes a **JSON string** and parses it to a JavaScript object
## Example Convert Javscript object into a string ``` var json = { person: { name: "bob", age: 20 } }; console.log( JSON.stringify( json ) ); ``` Outputs: ``` {"person":{"name":"bob","age":20}} ```
## Example JSON String ``` var json = '{"person" : {"age":20, "name": "bob"}}'; ``` Convert to a Javascript object ``` var parsed = JSON.parse(json); ``` Test ``` console.log( parsed.person ); console.log( parsed.person["age"]); ```
Example (JSON Formatter)
Validator (Syntax Checker)/Compact View
## JSON vs XML Both have been used to communicate data * JSON is valid JavaScript; better with JavaScript/Web than XML
* JSON less verbose and light weight * XML can be used as a more general purpose markup
* XML usually specialized XML vocabulary is used * JSON is much more universal in this regard
## AJAX ![](./images/ajaxpic.jpg)
## **AJAX** * AJAX is **not** a programming language * AJAX is a technique for accessing web servers from a web page * AJAX stands for **Asynchronous JavaScript And XML**
## AJAX * Technique for creating **interactive web pages** * JavaScript and **XMLHttpRequest** to interchange and manipulate data with web server * **Asynchronous** communication (i.e., no freezing up)
## Revision Question AJAX stands for? * A. Abstract JavaScript Asynchronous XML * B. Abstract JavaScript Adverse XML * C. Asynchronous JavaScript Archive XML * D. Asynchronous JavaScript And XML
## Answer Answer: **D.** Asynchronous JavaScript And XML
## AJAX request XMLHttpRequest is used to create and send HTTP requests 1. Create XMLHttpRequest: ``` let xhr = new XMLHttpRequest() ``` 2. configure the request ``` xhr.open(method, URL, [async, user, password]) ``` 3. connect to server and send the request ``` xhr.send([body]) ``` 4. Listen to events for response **load , error , progress**
## POST and GET in AJAX * GET places arguments in **query string** (POST doesn't) * GET call in AJAX has **size limitation** on the amount of data that can be passed
## POST and GET in AJAX General Principle * GET method: it is used to **retrieve data** to display in the page and data is not expected to be changed on the server * POST method: to update information on the server (**send**)
## AJAX Methods * **open**("method", "URL"[,async[, "userName"[, "password"]]]): - Initializes a request. * **send**([body]): Connect to server and Sends the request. - If the request is asynchronous(which is default), this method return as soon as the request is sent - If the request is synchronous, this method doesn't return unilt the response has arrived
## AJAX Callbacks * **onload** ``` xhr.onload = function() { ... ``` * **onerror** ``` xhr.onerror = function() { alert("Request failed"); }; ``` * **onprogress** ``` xhr.onprogress = function(event) { ``` * addEventListener(event, Callback) event : "load", "error", ...
## AJAX Response Receive the result in the following xhr properties: * **status** - HTTP status code: 200, 404, 403, ... * **statusText** - HTTP status message: OK, Not Found, Forbidden, ... * **response / responseText / responseXML ...** - the response body ``` xhr.onload = function() { if (xhr.status != 200) { alert(`Error ${xhr.status}: ${xhr.statusText}`); } else { alert(xhr.response); } }; ``` * **responseType** - enumerated string value: arrayBuffer, json, document, text
## Example ```
AJAX Test