Using jQuery to do some cool CSS and DOM tricks is fun, but soon you’ll need to read information (or data) from a server and display it. You may even have to update small pieces of the page with the information from the server, without having to reload the page. Enter Ajax. Combined with jQuery and JavaScript, it can do just that. In this chapter, we’ll learn how jQuery deals with making Ajax calls to the server and what it can do with the information returned.
Subject: 42nd Annual Bit to Byte Race results page |
Hey Web Design Team, |
As you’re all aware, every year we sponsor Webville’s Annual Bit to Byte 10K run by providing the race results page. But our page is way behind the times, as we only update it after all the results are in. People want instant gratification, and with Twitter and Facebook, folks attending the race are beating us at providing real-time results. |
So we’ve got a challenge for you with a sweet payoff. If you can update our Webville Results page by next week to provide real-time results, you’ll get to hang out in the VIP section at the end of the race. (Oh, and did we mention the race is in Maui this year?) |
Here’s what we need:
|
It doesn’t look super different from last year’s page, so that would be a good place to start. This is a great event, so we can’t wait to see what you come up with! |
-- |
Dionah C. Housney Head of Marketing Webville MegaCorp |
Let’s have a look at last year’s page to see how it was set up and what it looked like, so we can understand better what is being asked by the marketing department.
Plug-ins are extensions to the base jQuery library that improve functionality, or make specific functions or tasks easier. In the example above, in combination with our CSS, the idTabs
plug-in converts our ul
element into clickable tabs and tells the a
links in our li
s which div
elements to show when they are clicked. This particular plug-in gives us a very easy-to-use navigation structure for our page, so we can keep different types of information visually separate but still use the same display area.
Don’t worry too much about the plug-in.
Plug-ins provide additional functionality to the default jQuery library. We’ll look more at these in Chapter 10, but for now let’s see what this one can do to speed up our project for us...
The marketing team wants the page to update in almost real time, so those hardcoded results in the HTML file have to go. And they only used JavaScript to update the time on the page! This is the perfect opportunity to take your jQuery to the next level. Welcome to the next generation of web apps, where jQuery, JavaScript, and a little bit of Ajax and XML can make your applications feel like dynamic (basically, the opposite of static), responsive desktop apps.
Ajax, which stands for “Asynchronous JavaScript and XML,” is a way of passing data in a structured format between a web server and a browser, without interfering with the website visitor. With Ajax, your pages and applications only ask the server for what they really need—just the parts of a page that need to change, and just the data for those parts that the server has to provide. That means less traffic, smaller updates, and less time sitting around waiting for page refreshes.
And best of all, an Ajax page is built using standard Internet technologies, things you have already seen in this book, or already know how to use, like:
HTML
CSS
JavaScript
The DOM
To use Ajax, we’ll look at a data format that’s been around for a while (XML) and jQuery’s method of handling Ajax requests, ajax
.
When you use Ajax, your web pages only ask the server for what they really need, when (and where) they need it.
Despite knowing some jQuery now, dealing with data threatens to drag us back into the days of the old web, where we had to refresh the whole page, or link to a completely separate page, in order to get some or all of the data to update. And then we’d be back to websites that seem sluggish, as the whole page has to be requested from the server each time. What’s the point of learning a bunch of cool jQuery if handling data is just going to slow us down again?
As we mentioned earlier, Ajax is a way of passing data in a structured format between a web server and a browser, without interfering with the website visitor. But, really, it isn’t one thing—it is a combination of different technologies used to build exciting, interactive web applications. The JavaScript portion allows it to interact with the DOM structure of your page. Asynchronous means it can happen in the background, without interfering with your page or a user interacting with your page. And the X is all about the data.
Yes, you could use HTML. But for the transfer of information, XML offers some unique benefits over its sister language, HTML. Let’s have a look to see what those benefits are.
XML is an acronym for eXtensible Markup Language. It offers a widely adopted, standard way of representing text and data in a format that can be processed without much human interaction. Information formatted in XML can be exchanged across platforms, applications, and even across both programming and written languages. It can also be used with a wide range of development tools and utilities. XML is easy to create and edit; all you need is a simple text editor, and the XML declaration at the top of the file. The rest is up to you!
It may sound a little strange, but XML doesn’t really do much itself. XML structures and stores information for transportation. In fact, XML is really a metalanguage for describing markup languages. In other words, XML provides a facility to define tags and the structural relationships between them. It is important to understand that XML is not a replacement for HTML. XML is a complement to HTML. In many web applications, XML is used to format data for transport, while HTML is used to format and display the data. Let’s take a closer look at an XML file that contains data about some books.
XML is used to format data for transportation, while HTML is used to format and display data.
You’re right.
Let’s get that out of the way, so we can get on to adding some Ajax to our page...
You want data? jQuery and Ajax are primed to provide it for you. The jQuery Ajax method returns an object (you remember those from Chapter 6, right?) with data about the particular action you are trying to perform. The ajax
method can accept many different parameters, and can POST data to or GET data from a server.
For a complete list of all the parameters available on this method, visit the jQuery docs site at http://api.jquery.com/jQuery.ajax/. There are also a series of jQuery convenience methods for dealing with Ajax calls. We’ll get to those a bit later, we promise.
For now, just update your my_scripts.js file with this code, only including the new code in bold below.
Ajax calls are subject to the same-origin policy!
The same-origin policy is a security concept for JavaScript and other client-side scripting languages. It allows scripts running on the page to access resources, like element properties and methods, that originate from the same server. It prevents scripts from accessing elements on pages that did not come from the same server. Due to legacy compatibility, JavaScript includes are not subject to these checks, but the XML file in the example is. That means the XML file must be on the same server as the page loading it.
We need a method to pick out each runner from our XML file and be able to display it on the screen. Luckily, jQuery supplies us with the find
method, whose job it is to seek out elements that match whatever criteria we give it. find
allows us to search through the descendants of elements in a structured, hierarchical set of information, like the DOM tree or an XML document, and construct a new array with the matching elements. The find
and children
methods are similar (we looked at the children
method back in Chapter 4, when we were building the menu for the Webville Eatery), except that the latter only travels a single level down the DOM tree. And we might need to go further...
By combining the find method with the each method, we can search for a group of elements and interact with each one individually, using a loop.
In the last chapter, we saw that both JavaScript and jQuery offer timer methods that call functions that run based on time passing. JavaScript’s window object has four timer methods for timed control: setTimeout
, clearTimeout
, setInterval
, and clearInterval
. jQuery provides the delay
method, but it focuses on effects and offers no option for scheduling or repeating actions. So, that one won’t help us here...
Not so fast!
We can’t always be so sure. setInterval
normally would work to schedule regular events on a page, but when dependent on outside resources (like our data file), it can cause problems.
setInterval
will run even if the function it is calling isn’t finished yet.
If you’re waiting on information from another server, or waiting on user interaction, setInterval
could call your function again before you’re ready. Your functions may not always return in the order that you called them.
A self-referencing function calls itself during its normal operations. Such functions can be particularly useful when you need to wait for the function’s currently running operation to complete before running it again. Combine this with a setTimeout
call, and you can schedule a function to run but only keep going if the previous call to the function was successful. Otherwise, it won’t reach the call to itself in the code, and hence it won’t be called again.
As we’ve seen so far, HTML is great for displaying information on a page and XML is great for formatting data for transportation to a page, but what if you need your page to actually do something, like tell the time or get data from a database? Sure, we could probably do some more fun things with jQuery and JavaScript, but why not use something designed for the job?
There are several different types of server-side languages—like JSP, ASP, or Cold Fusion—but we’re only going to focus on one for our purposes: PHP.
PHP (which stands for PHP: Hypertext Processor—yes, that’s an acronym within an acronym; don’t ask us why!) is a free, general-purpose, server-side scripting language used to produce dynamic web pages. Files that contain PHP code are run on the server, and produce HTML that is then provided to a browser to render. We’ll look at PHP in a little more detail in the next chapter, but for now we’ll see how it can help us with our “updated time” feature.
PHP is used to dynamically produce HTML, which is then displayed in the browser.
OK, we’ll confess, there is already a JavaScript function we could use to get the time. But it is a large, complicated function for doing something so simple. Luckily, PHP gives us a very easy way of getting the time, using the date
function. Just like the functions you have created up to this point, it takes multiple parameters and returns a different version of the date, depending on what parameters you pass in. The main parameter determines how you want the date to be displayed. Let’s have a closer look:
For a complete listing of the parameters of the date
function, visit http://php.net/manual/en/function.date.php.
Do this!
Create a new file in the same folder as your index.html file, and call it time.php. Add the following code to your new time.php file.
Back in Chapter 5 and Chapter 7, we created a “monster” function by using setTimeout
to continuously call the functions that produced the lightning effects. This led to some unexpected consequences—the page lost focus and the visual effects piled on top of one another when someone returned to the app.
However, since we already determined that we need to wait until the previous call to the function is finished, we can’t switch to using setInterval
for these calls.
We need to come up with a better solution. And what better solution than one we’ve already seen? We can’t use the window.onblur
and window.onfocus
browser events, since we don’t want people to have to leave in order to stop the updating. But we have already seen, across several chapters, how to run code based on conditional logic, so let’s use that for our solution here as well.
You’ve got Chapter 8 under your belt and you’ve added a little PHP, some XML, and a bunch of Ajax to your toolbox.
A combination of technologies that allow you to update a portion of a web page without having to reload the whole page.
Makes calls to a backend server that can process data before sending it back.
jQuery implements Ajax functionality through the ajax method.
There are five shortcuts for ajax in jQuery, all configured to have different parameters by default, but ultimately calling the ajax method:
$.get
$.getJSON
$.getScript
$.post
$.load
3.144.227.9