-
-
Save rvvvt/8eeb33f9a33aac98e984e6942fbc4b7c to your computer and use it in GitHub Desktop.
All about AJAX and JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Learn all about AJAX - post on public github | |
// first, the vanilla JavaScript approach ( before jQuery ) | |
// initialise new XMLHttpRequest() object | |
var xhr = new XMLHttpRequest(); | |
// check if AJAX request is completed | |
// state 4 = completed request | |
xhr.onreadystatechange = function(){ | |
if(xhr.readyState === 4){ | |
// can check if xhr.statuscode === 200 OK | |
// insert HTML manipulation here | |
document.getElementById('foo').innerHTML = xhr.responseText; | |
// Parsing JSON data - data from server in JSON format is just a string, thus the need for JSON.parse to turn it into something JavaScript recognises | |
/* | |
// employees now hold an array of Objects - JSON data | |
var employees = JSON.parse(xhr.responseText); | |
*/ | |
} | |
} | |
// open a request to the server, type followed by URL + optional query string (?lastName=Jones) | |
xhr.open('GET','http://api.example.com/employees?lastName=Jones'); | |
// send the request to the server | |
xhr.send(); | |
// second, AJAX with jQuery | |
// .load jQuery method for AJAX calls | |
// $.get(url,data,callback) is a more sophisticated AJAX GET call | |
function sendAJAX(){ | |
// find div id="sidebarid" and append sidebar.html onto it | |
$('#sidebarid').load('sidebar.html'); | |
} | |
$(document).ready(function(){ | |
$.getJSON(url,data,callback); // end getJSON | |
}); // end ready | |
// jQuery for loop method | |
$.each(array_or_object,callback); | |
// JavaScript | |
document.getElementById('employeeList').innerHTML = statusHTML; | |
// jQuery add to HTML method | |
$('#employeeList').html(statusHTML); | |
// jQuery post method | |
var url = "http://example.com/posts"; | |
var data = {"tesha":"don't quite understand how this works"}; | |
$.post(url,data,callback); | |
// jQuery - how to get data from a form, also how to transform the page when the user presses the form submit button without going to a new page (AJAX) | |
$(document).ready(function(){ | |
$('form').submit(function(evt){ | |
evt.preventDefault(); // prevents the form from submitting the data | |
var url = $(this).attr("action"); // get the url from the action tag of the form | |
var formData = $(this).serialize(); // make form data usable | |
$.post(url,formData,function(response){ | |
$('#signup').html("<p>Thanks for signing up!</p>"); | |
}); // end post | |
}); // end submit | |
}); // end ready | |
// $.ajax is shorthand for jQuery.ajax | |
// jQuery - the ultimate AJAX method, $ajax, one method to rule them all - able to GET, POST etc with this method | |
$.ajax(url,parameters); | |
$.ajax(url,{ | |
data : formData, | |
type : "POST", | |
success : function(response){ | |
$('#signup').html("<p>Thanks for signing up!</p>"); | |
} | |
}).fail(function(jqXHR){ | |
alert(jqXHR.status); | |
}); | |
// .fail method to notify user that something went wrong, doesn't work with .load and JSONP | |
// Chrome extension JSONViewer ( beautifies JSON data ) + web app JSON checker | |
// JSON example - to refresh your memory on how to manipulate it, copy paste it onto console to get a better understanding | |
var VII = [ | |
{ "firstname": "Rey", | |
"lastname" : "Skywalker", | |
"abilities" : ["imba_shit","hot","blue_lightsaber"] | |
}, | |
{ | |
"firstname": "Kylo", | |
"lastname" : "Ren", | |
"abilities" : ["fking pussy","whiny brat","I just stopped a blaster shot...SWAG"] | |
} | |
] | |
// let's see what it does now | |
VII[0] -> returns Object[0], Object{firstname:"Rey","lastname"........} | |
VII[0].firstname -> // returns "Rey" | |
VII[0].abilities -> // returns an array of Rey's abilities | |
VII[0].abilities[0] -> "imba_shit" | |
// Flickr getJSON example | |
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; | |
var animal = $(this).text(); | |
var flickrOptions = { | |
tags : animal, | |
format: "json" | |
} | |
function displayPhotos(data){ | |
// do something here... | |
} | |
$.getJSON(flickerAPI,flickrOptions,displayPhotos); // $.getJSON(url,data,function_callback) | |
// AJAX same origin policy ------- CORS | |
HTTP != HTTPS | |
www < home server > != non www < home server > | |
< foreign server > = disallowed | |
Ways to circumvent same origin policy problem | |
1. Use a web proxy - write a script utilising the home server to talk with a foreign server, foreign server sends AJAX response to home server, home server sends the response to client | |
2. JSONP - JSON with Padding | |
<script src="http........"></script> | |
3. CORS - Cross-Origin Resource Sharing | |
Settings on < foreign server > --> < Access-Control-Allow-Origin: http://www.myserver.com > + access credentials ( API tokens, passwords etc...) | |
// cool tricks for debugging | |
// debugger method JavaScript - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment