AJAX with JSON and jQuery

Javascript Object Notation

  • Uses basic JavaScript arrays and objects to store data.
  • Can either be formatted using array or object notation or a combo of both.

JSON objects vs arrays

Creates key/value pairs to help distinguish what data is in the array.

JSON Formatted data

JSON properties must be enclosed in double-quotes.
[
{
"name": "Aimee",
"inOffice": "true",
},
{
"name": "Bob",
"inOffice": "true",
},
{
"name": "Carl",
"inOffice": "false",
},
]

Use a validator like JSONLint to check if the JSON is formatted correctly.

Parsing JSON

JSON data is just a string of text and needs to be converted to JavaScript (parsing). Takes a string and converts it into a JavaScript object.

JSON.parse(xhr.responseText)

Processing JSON

Using JavaScript

var statusHTML = "<ul>";for (var i=0; i < jsonObject.length; i ++) {
statusHTML += "<li>" . jsonObject[i].keyname . "</li>";
}
status HTML += "ul";

Using jQuery

jQuery has a method function that rolls all four steps of a usual AJAX request into one:

function sendAJAX() {
$('#ajax').load(sidebar.html)
}

jQuery has a number of shorthand methods to simplify using AJAX. These are documented on the jQuery API reference website.

The get method

The get method does not require an element to be selected first.

var url = "/employees.html';
The URL you are making the request to. (as you would use in the js Open method)

var data ={firstName : "Dave", lastName : "McFarland"}
In the form of a query string, the data that would be added to the query string appended to the URL

var callback = function(response){
// Do something with the ajax response
}

$.get(url, data, callback);

getJSON method

$.getJSON(url, data, callback);

The data needs to be in JSON format. The method will automatically parse the JSON data returned. Process the response using the jQuery each method.

$.each(array_or_object, callback) ;

$.each(response, function(index, value) {});

post method

$.post(url,data,callback);

$('form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize(); //creates a text string with standar URL-encoded notation of fields in an HTML form
$.post(url, formData, function(response{
$('#signup').html(');
});

ajax method

$.ajax(url,settings);

The ultimate (low-level) AJAX method. Requires a url parameter and a JavaScript object containing settings for how the AJAX request should be handled. Refer to the online documentation for all the settings.
$.ajax(url, {
data : formData,
type : "POST",
success : function(response) {
$('#signup").html(<p>Thanks for signing up!</p&gt")
}
});

Handling Errors with jQuery & Ajax

.fail method

A chainable method – jqXHR will return the error.

$.get('missing.html',function(data){ $('#myDiv').html(data); }).fail(function (jqXHR) { alert(jqXHR.statusText)});});

Doesn’t work for a $.load() method and doesn’t work when using JSONP

 

Better to use Fetch API

Ajax – Basics

AJAX stands for Asynchronous Javascript and XML

also knowns as …

XML HTTP Request (XHR)

The AJAX/XHR process consists of the following:

  1. Create an XML HTTP Request object
  2. Create a Callback function
  3. Open a Request
  4. Send the Request (to a webserver)
Creating an xml http request object

This is done by creating an object variable using the XMLHttpRequest() function:

var xhr = new XMLHttpRequest();

Creating a callback function

Create a function that will be called once ready state has changed to status 4:

xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//action
}
};

OPen a request

Use the .open() function:. eg:

xhr.open('GET', 'sidebar.html');

Send the Request

Pass info to send (in the parenthesis) to the server:

xhr.send();


Ready State and Callbacks

Each stage of the process involves a readyState. Each step changes the ready stage of the request. A callback responds to the change in that state

An XML HTTP request object’s readyState property holds a number from 0 to 4. Zero to 3 represents stages from when the object is created to when the response is coming. ReadyState 4 is when the web server has sent everything it’s going to send.

Status Property

The object also returns a status as per the following

200 – 0k

401 – not authorised

404 – not found

500 – database  error

eg. To create a callback when the status is ok. The status has a property of .statusText to provide further info:

if (xhr.status === 200) {

//action

} else {
alert(xhr.statusText);
}

Displaying results

Use the XHR object’s responseText property:
xhr.responseText;