{
"firstName": "Jane",
"lastName": "Smith",
"address": {
"streetAddress": "425 2nd Street",
"city": "San Francisco",
"state": "CA",
"postalCode": 94107
},
"phoneNumbers": [
"212 732-1234",
"646 123-4567" ]
}
Start by storing JSON in a variable:
var myProfile = {
"firstName": "Natalie",
"lastName": "MacLees",
"cats": ["Mabel", "Ollie"]};
Then, you can access the data stored inside and use it while creating new nodes:
var p = document.createElement('p');
p.innerHTML = 'My name is ' + myProfile.firstName + ' ' + myProfile.lastName + '. ';
p.innerHTML += 'My cats are ' + myProfile.cats.join(' and ') + '.';
var body = document.getElementsByTagName('body')[0];
body.appendChild(p);
Questions about JSON?
Asynchronous JavaScript And "XML"
We're going to start writing some ajax now.
If you haven't already, get a local server running.
XMLHttpRequest
objectvar request = new XMLHttpRequest();
Now that we've created an instance of the XHR object, it needs to be prepped for communication. That requires three things:
readystatechange
event handleropen()
methodsend()
methodreadystatechange
readyState
.readyState
property is changed, the readystatechange
event is fired.readystatechange
event, your function will execute each time the server pings the client with an update.onreadystatechange
examplevar request = new XMLHttpRequest();
if(request) {
request.addEventListener('readystatechange', function(){
console.log(request.readyState);
});
}
open()
methodThe open()
method takes two required arguments:
And an additional optional argument:
open()
methodvar request = new XMLHttpRequest();
if(request) {
request.addEventListener('readystatechange', function(){
console.log(request.readyState);
});
request.open('GET', 'me.json', true);
}
Here's a me.json file you can include in your project to call.
GET
and POST
GET
POST
Just FYI, there are some other request types too (PUT
, DELETE
, and HEAD
, for example), but they're not a concern for the stuff we're doing.
If we're on this page:
http://store.company.com/dir/page.html
Here's how these ajax requests will work out:
URL | Outcome | Reason |
---|---|---|
http://store.company.com/dir2/other.html | Success | |
http://store.company.com/dir/inner/other.html | Success | |
https://store.company.com/secure.html | Failure | Different protocol |
http://store.company.com:81/dir/etc.html | Failure | Different port |
http://news.company.com/dir/other.html | Failure | Different host |
http://google.com | Failure | Different host |
Indicates whether the request should occur asynchronously or not.
If true
, the script will make the request and won't wait for the response from the server before moving on to the rest of the script.
If false
, the browser will stop processing the script until the ajax request is completed.
Use true
!
send()
methodOnce your request is prepped by the open()
method, it's ready to be sent!
send()
using GET
var request = new XMLHttpRequest();
if(request) {
request.addEventListener('readystatechange', function(){
console.log(request.readyState);
});
request.open('GET', 'me.json', true);
request.send();
}
Here's a me.json file you can include in your project to call.
POST
: The setRequestHeader()
methodSince we're sending data with the POST
type, we have an extra step. We need to use the setRequestHeader
method of the XHR object to set the request headers.
Request headers are bits of metadata that describe the request so the server understands what to expect from the data received.
setRequestHeader()
takes two arguments:
setRequestHeader()
exampleIf you are sending data to the server, you need to set the value of the Content-type
header to application/x-www-form-urlencoded
, like this:
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
This tells the server to expect some data and for that data to be URL-encoded.
URL-encoded means spaces become plus signs (+) and non-alphanumeric characters need to be encoded as hex values.
'name=Natalie+MacLees&message=JavaScript+is+awesome%21'
send()
using POST
var request = new XMLHttpRequest();
if(request) {
request.addEventListener('readystatechange', function(){
console.log(request.readyState);
});
request.open('POST', 'me.php', true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send('name=Natalie+MacLees&message=JavaScript+is+awesome%21');
}
In your project folder, create a simple .txt
file with a sentence of plain text in it.
Next, set up a new XHR object and get the file. Use the console tools to view the request.
Phew! Now we've got sending a request down - let's learn how to receive a response!
readyState
propertyIndicates the current state of the Ajax request. Possible values:
0
- Uninitialized. The open method hasn't been called yet.1
- Loading. The open method has been called.2
- Loaded. The send method has been called - the request has begun3
- Interactive. The server is working on it4
- Complete. The server sent a response.readyState
property and the readyStateChange
eventIn theory, the readyState property counts from 0 to 4 in order.
In practice, what happens is a bit unpredictable.
What we can count on is that if the value has reached 4
, the server has finished sending a response.
readyState
var request = new XMLHttpRequest();
var doSomething = function() {
if (request.readyState == 4) {
console.log('The request is complete!');
//do something with the response here
}
}
if(request) {
request.addEventListener('readystatechange', doSomething);
request.open('GET', 'me.json', true);
request.send();
}
doSomething()
gets called every time the value of the readyState
property changes, but our if
statement ensures nothing will happen unless the value is 4
.
When the server sends back a response, it always includes response headers with metadata about the response.
These headers include a status code - a three digit number that is part of the HTTP protocol
Some examples:
404
- not found403
- forbidden500
- internal server errorThe most common status code is 200
, which means OK
. It indicates the response was successfully sent.
The XHR object has a property called status
where the status code is stored. We can check it to make sure we got a successful response:
var doSomething = function() {
if(request.readyState == 4) {
if(request.status == 200) {
console.log('The request is complete and ok.');
//do something with the response here
}
}
}
We can also add an else
statement to deal with situations where things don't go according to plan:
var doSomething = function() {
if(request.readyState == 4) {
if(request.status == 200) {
console.log('The request is complete and ok.');
//do something with the response here
} else {
//something went wrong
}
}
}
responseText
propertyThe responseText
property of the XHR object contains the data sent from the server as a string.
var doSomething = function() {
if(request.readyState == 4) {
if(request.status == 200) {
console.log(request.responseText);
}
}
}
The responseText
property contains our data, but it's a string, and we need JSON. We just need to convert it to JSON like this:
var jsonObj = JSON.parse(request.responseText);
Let's step through fetching some information from the server with ajax and displaying it on our page.
var request = new XMLHttpRequest();
var displayResponse = function(){
// we'll write some code here later
};
if (request) {
request.addEventListener('readystatechange', displayResponse);
request.open('GET', 'me.json', true);
request.send();
}
<div id="resultsBox"></div>
var displayResponse = function(){
if (request.readyState == 4) {
if (request.status == 200) {
var jsonObj = JSON.parse(request.responseText);
var p = document.createElement('p');
p.innerHTML = 'My name is ' + jsonObj.firstName + ' ' + jsonObj.lastName + ' and I live at ' + jsonObj.address.streetAddress + ' in ' + jsonObj.address.city + '. ';
p.innerHTML += 'My zip code is ' + jsonObj.address.postalCode + '.';
var displayBox = document.getElementById('resultsBox');
displayBox.appendChild(p);
}
}
};
We're using what we already learned about dealing with JSON!
The XMLHttpRequest
is the heart and soul of ajax. Its methods and properties drive the requests that make ajax feel so responsive.
Questions about JSON or Ajax before we wrap up?
We strive to make every class better than the last. We rely on your honest feedback to make our classes better. Please take a moment to complete the survey for this class.
As you keep working with JavaScript, if you have questions or get stuck, post in our Facebook group and we'll help you out!.