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>")
}
});
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