AJAX stands for Asynchronous JS And XML. It lets you update html without loading a new webpage. Examples include when you load google maps, then search for a new location and the map/ui change. Or, in twitter with it’s endlessly loading tweets as you scroll down. Or, when you upvote something on reddit.
Normally, you get more web content by loading a new webpage. AJAX is faster and easier, the web page requests info from the web server (the Request), which then returns the data to the web browser (the Response), which JS then uses to selectively change parts of the web page. The amount of data returned is usually much less than a full web page.
To see a pages AJAX requests, open the JS console > right click > Log XMLhttp requests. XHR is short for XML http requests. AJAX isn’t actually its official name. Technically it’s called the XMLHttpRequest Object, or XHR. Example: you sign up for a newsletter, the page sends a request and the server does something, like adds your email to a database, then sends a response which makes the page display a “success” message.
JS is the programming language used to make AJAX happen. It’s used to send out a AJAX request, process the incoming response, then also to update the page. The asynchronous refers to how the request is sent to the server. They are sent without waiting, otherwise they would freeze your browser until you got a response back (which might not even happen). With asynchronous, the page continues loading regardless. This let’s you send out multiple requests, and you won’t know which will come back first. They’re affected by the speed of the server, the complexity of the request and any internet traffic. XML stands for extendable mark up language.
There are four steps.
1. Create an XMLHTTP object – tells the web browser to get ready, you want to send an AJAX request and the browser needs to create an object that has all the methods needed to send and receive data.
2. Create a callback function – This is the programming you want to run when the server returns its response. The callback is where you process the return data, and update the HTML on the page. This is the heart of AJAX.
3. Open a request – here you give the browser two pieces of information, the method the browser will use to send the request (usually GET or POST), and the URL where the request is sent.
4. Send the request – The last three steps gave the browser everything it needs, so we can finally send the request.
A simply AJAX example
You can just use AJAX locally. You’ll need to set up a web server either locally or a normal one.
We start by writing JS. Step 1 – make XMLHTTP object – We declare a variable and set it to new XMLHttpRequest(). You need to do this for each request you want to send. So if you wanted to send two, you’d need two variables, each with their own XMLHttpRequest()’s.
Step 2 – create a callback function – This uses and event listener similar to what we saw before for mouseclicks, scrolling, keypresses etc, and is .onreadystatechange. It runs its function each time there is a change in the state of an AJAX request, which can be sending the request, receiving the response, etc. The readyState property on the XMLHttpRequest() object holds a number 0-4 showing the current state of the request, and when it’s done, that number is 4. We then create an if block that reads true if the state is 4.
Then, we want to enter the html received by the server into a div, which we can do with document.getElementByID(‘ajax;) and set its innerHTML property, which contains all the HTML inside it, and by changing its value we change the html inside it. So, we’ll set that equal to xhr.responseText. Every XML HTTP request object has a property called response text, which is the information the server sends back. So, we’re taking that and setting it equal to the innerHTML, so it will become the div’s html.
Remember, the programing won’t run until the response comes back from the server.
Step 3 – open a request – xhr (the variable we’re calling our XMLHTTP object) has a function called .open, which you give two pieces of information, the http method, and the url you want it to go to, which can be a file, etc. In the example below we’re getting the sidebar.html file.
Step 4 – sending the request – here we use the send() function. Since we’re requesting info (GET), we don’t need to provide the function with anything, but if we were sending stuff (POST, PUT), we would need to.
This isn’t very interactive though. Let’s make it so it loads upon clicking a button. First we’ll add the button to the markup, give it an id and set it’s onclick attribute to a function sendAJAX().
Then we’ll create the function and make it so when the function runs it send the request, and also so that the button itself disappears. Note how the latter is different than jQuery, where you would just use .hide(). Here you need to select the display property and set it to “none”.
GET and POST
Opening a request requires specifying the method you want to use to send the request. GET is used when you only need to receive info from a server. Use POST when you need to send info, like a reddit vote or an email sign up for a newsletter. When you go to a website, the browser actually uses a GET to get the web page.
However, usually things need to be dynamic and have you send and receive info, like when using google maps, you put in your address, it updates the map, etc. You can do this with GET and its url. The part after the question mark is called a query string. It lets you send additional info that the web server can use to control the output of its response. Commonly it’s used to search a database of info and return a single record or a small subset.
Query strings are made up of one or more name/property value pairs. You separate them with ampersands (&).
There are rules on what characters you can use. &, space, quotes and + have special meanings in a URL so if you want to use them you have to encode them, which translates them into a set of safe symbols that won’t conflict with their normal meaning.
There are sites online to help you with this, like this one.
Now, an issue with doing this is that all the info needs to be sent via the url, which is bad if it’s sensitive data. It’s not very secure as it will show up in the servers log files. Also, there is a char limit for urls in some browsers.
The POST method is better for sending large amounts of info. Rather than sending the info in the url like GET does, it puts it in the body of the request, separate from the url. It also requires a special header for the request, which is a special instruction to the server telling it what type of data to expect.
AJAX Response Formats
It can be a text message, like “OK”, or “Message Received”. Or it can be a static file, which is one just sitting on the server, like the bit of html we got in the practical example above.
But what if you get a lot of data? It’s good to have a structured format. This means it’s ordered consistently, has identifiers that indicate what the data is, and is easy for JS to analyze and use. The process of breaking a file up into easily accessed parts is called parsing. Two common formats are XML and JSON.
XML is extensible markup language, which apparently let’s you make up your own tags. That shit cray.
However, XML is tough to use with JS, so we use JSON instead.
AJAX Security Limitations
It’s limited by the browsers same origin policy, which controls how JS can access content from a web server. In general, you can use AJAX to communicate from one page to another on the same web server, but not to access other web servers. If you try to request info from a different server than the one the site is hosted on, it’s another origin and it’s forbidden. Or, if yours is http and that one is https, it’s not allowed. You also can’t do one with a different port than yours. Or, one with a different host, meaning http://www.domain.com vs db.domain.com.
But what if you want something on your site from a different one, like a google map or a tweet? There are a few ways to circumvent the same origin policy, like a web proxy. Web servers aren’t limited by the same origin policy, so you can have your server ask for info from another one using php or ruby.
Another way is JSOP – JSON with Padding, where you basically link to a JS file across another domain. An example is jQuery. Instead of actually using AJAX to contact another web server, you load a JS file from the other site.
Finally there’s CORS – Cross Origin Resource Sharing, which is a W3C recommendation. It requires some set up on the server’s part, but it allows a server to accept requests from other domains. It also allows for more complex forms of authentication, requiring the web browser to supply credentials before the server will provide any info.
Last limitation – AJAX won’t work unless you’re viewing the page via a web server.
This project will have you add a sidebar to your companies intranet that says whether an employee is in or out of the office.
Remember, the readyState property can be 0 to 4, with 0 being when the XMLHttp object has been created, with 3 being when the response is coming, and with 4 being the server has sent everything it’s going to send for the response. In our previous example, we set the callback function to run when the readyState was 4, but sometimes that’s not enough, something may have gone wrong. The web server can’t connect to the database, the web program handling the request crashes, or the AJAX pointed to a file that can’t be found. If any of these happen the browser won’t receive the response with the info needed.
So, we can expand the conditional statement by checking another property of the request object, the status property,which is a number sent from the server telling you about how things went.
- 200 means okay, and is the standard response for a successful http request
- 404 is for file not found
- 401 is not authorized to access a url due to a log in requirement or permission needed
- 500 is when the server has an error, usually when its programming isn’t working.
So now nothing happens unless we get the response and the request is sent successfully. But, you can adjust it for if things go wrong.
Accompanying the status object is the statusText, which is an explanation of the status. You can use this as part of the error message you display to the user. Here, we’ll use an else block to make it so that anytime you get something other than a 200 message, it gives an alert error message. To test this, we’ll change the .open to look for a file that’s not there.
In some cases, you won’t need any error message.
An object is made up of key value pairs which fixes this. The key is the name of the property, and then you set its value. The key is separated from it’s value by a colon, and you separate the pairs with commas, except for the last one.
While this look just like the objects we did with JS, there is an extra requirement for JSON formatted data. In regular JS, keys don’t have to be quoted, but in JSON they do and require double quotes. Also, strings require double quotes as well.
Now to get to work on the project. We’ll create an array, and then put objects into the array, since objects are just as valid as strings, numbers, etc for an array. JSON is picky, so if you mess up with the formatting, you’ll usually end up with a JS error. You can use an online validator to check your JSON, like this one. You won’t ever really have to write JSON by hand, it’ll usually be written programmatically by the web server.
Even though JSON is formatted to look like JS, it isn’t – it’s a plain text string, with no significance to your web browser. We need to take it and convert it into JS, a process known as parsing. All web browsers can do it using one command.
We’ll start by creating a XMLHttpRequest object, and then set up the callback function to run when the readyState property is at 4. Then we’ll do our steps 3 and 4 to open the request and then send it.
Now, let’s set up the actual code for the callback function that we want to run. We’ll get the responseText property of our xhr object, and set it in a console.log so we can see what it actually is saying. We then link our js file to our html one in the head, and we get this when we run the page.
In the console, you can see it loaded our file. It looks like JS, but it isn’t yet. We can check this using the typeof operator, which looks at the type of the thing list after it.
To turn it into real JS, use the JSON.parse method, which takes a string and tries to convert it into a JS object. Remember, JSON is picky and this won’t work unless it’s formatted correctly. You’d get a JS error.
To check this, let’s first see the type of element the employees variable is.
Note – in JS arrays are considered a type of object. Next, let’s see whats inside the object.
Ok, we start by looking at the final html/css we’ll want. It’ll be a simple unordered list, and if they’re in, they get a class of in, and if they’re out they get a class of out. We’ll use the before and after pseudo-classes to display the icons. To build the html, we need to generate from the JSON one list item for each person in the company.
We’ll start by declaring a variable, and setting it equal to an opening ul tag. Next, we’ll build it up by adding more html to the variable, then eventually print it to our webpage.
Now we’ll create a for loop to run through the list of employees. It starts by setting a counter variable, i, to zero. The second is a test condition which will determine how many times the loop runs for. As long as i is less than the length of the employees array, the loop with continue to run. Lastly, after each time the loop runs, 1 is added to the variable i.
In an array you use the index to access each value. Rather than type that in ourselves, we can use the counter variable i from the loop.
To access properties in JS objects we use the dot syntax aka dot notation. Simply write the object, then a dot, then the property name. As i’s value changes, we’ll access different objects from the array.
Now, let’s start by checking if the employee is in the office with an if/else block, and add a opening tag list item with the appropriate class. The += operator in JS means take the current operator and add something to it. Next, we’ll add the name, and then close the tag. By the time the loop is done, it’s been filled with the list items. We can then add it to the div that’s already been set up to hold it.
They had me do another challenge where we did basically the same thing only with whether rooms were taken. Note – with each new variable you declare for xhr objects, you need a new variable name.