You are on page 1of 17

1

Ajax - Create a Single Page App with jQuery


Create your first Single-Page Application (SPA) with jQuery using AJAX.

In this lesson, we are going to learn how to create a single page application with
jQuery using the Ajax technique If you go to the Gmail and open any email, you notice that
the Gmail only loads the email, without loading the whole webpage. Only the content of the
email is modified in the Document object model or in the browser, and only that information
is pulled from the particular server and shown to the computer of the user.

No JavaScript, CSS or templates are reloaded. It basically speeds up the experience. It's less
processing on the server side, it's less processing on the client side so therefore the experience
is smoother. The same technique has been used on Twitter as well. If you click on someone's
following or followers, it loads the followers and followings without loading the whole
page. Both of the techniques are called the Ajax technique.

AJAX

Ajax stands for Asynchronous JavaScript and XML. Ajax is not a technology but a technique
which is used in web programming to transfer information over the internet. Asynchronous
means when the request is sent to the server for any kind of new data lets bring in the new
email or new followers etc. There's a delay when the server is processing and sending back
the information. To understand the XML part, go check out the JSON video

Examples of applications using AJAX technique: Gmail, Google Maps, Facebook and
YouTube etc.

Our HTML Document

You see our document has some basic HTML in it. I have the h1 tag and two links in it.
2

The about.html page doesn't have the full HTML, but only has one div with some content in
it.
3

This is how our page looks like.


4

If I click on about page, it will lead me to the next page like such
5

If I click on the contact page, it will lead us to the contact page. But we want to create a one-
page application so when I click on about, it shows the about me info on the same page if I
click on contact, it shows the contact info on the same page without loading the entire web
page.

Now I'll start writing code in our script.js file. If you haven't created the script file, go and
create one. In this lesson, we are going to look at the following Ajax methods.
6

$.ajax( ); is the core method that jQuery has. I have already pre-written some of the code
which I'm going to explain to you. The $.ajax( ); method has several parameters that you
can pass to it. The URL contains the page that we want our page to load. So in our case, it's
about.html as shown below in the screenshot

The data parameter is going to convert the id and its value to query string. On the World
Wide Web, a query string is the part of a (URL) containing data that does not fit conveniently
into a hierarchical path structure.

Structure
A typical URL containing a query string is as follows:
http://example.com/over/there?name=ferret

When a server receives a request for such a page, it may run a program, passing the query
string, which in this case is, name=ferret unchanged, to the program. The first question mark
is used as a separator, and is not part of the query string.

If I have about.html?id=123 and in many cases when you're making a request to the server
and you want to pass some data. For example you say, get the username with an id of 123 like
such about.html?id=123 that's the query string parameter we are going to use. We will
further look at it in the next lesson.
7

The other parameter is the type. In HTTP, there are two primary kinds of request that we
send. One is the 'Get' request and the one is the 'Post' request. The Get request simply gets the
image from the server or the HTML, CSS or script document.

The 'post' in other words is sending some data to the server for some processing. Where some
data has been sent o the server and there has been some change done.

In our case, we want to get the information so we will only use the about.html in the URL
parameter. I'm going to change the datatype to "HTML"

When the above request is successful, there's going to be a function which will run. I'm going
to console.log just for demonstration

success: function( response ) {


console.log('the page was loaded', response);
8

},

If the ajax response fails, then the function below will run

success: function( error ) {


console.log('the page was NOT loaded', error);
},

The complete function runs, regardless if the ajax was successful or failed

success: function( xhr, status ) {


console.log("the request is complete!", error);
},

Save it, refresh the screen and go to the Chrome developer tools and you will see there's an
9

error there. XMLHttpRequest cannot load. The reason for that is that the application we
have is not on a web server. We are accessing the file via local directory.

If you are on a MAC, you can use the terminal and luanch a web server. If you're on
Windows, you can download the app called mongoose server where you can simply double
click that particular app app and server gets loaded on that particular location where you
actually doubled clicked the mongoose server.
Whereas in MAC, you can write command python -m SimpleHTTPServer 8000
10

I'm going to put the localhost:8000/index.html hit enter and you see the page is loaded
and the error is gone
11

But you see there are two console. One is the page was NOT loaded and the one is The
response is completed. Let's see why the page was not loaded. The dataType should just be
text as shown below
12

Save it, refresh the screen and you see the content of the about me page has been logged in the
console.
13

In the HTML document, I have a div with a class of content which is empty. In the call back
function, I can append the information on the webpage like such

success: function( response ) {


console.log('the page was loaded', response);
$('.content').html(response);
},
Save it, refresh the screen and you see the page has been loaded
14

Now when I click on About or Contact, the page loads and goes to that particular page, which
we don't want. When we click on About page, the about page info should appear on the same
page.
I'm going to put the whole ajax method inside a function called callPage as shown below. The
code looks cleaner as I have removed the comments.
15

I'm going to write a simple on click function like whenever the anchor tag is clicked, run
the function. The function is going to be that when the page is clicked, it prevents the page
from going to another page.

$('a').on('click', function(e){
e.preventDefault( );
});
Save it, refresh the screen and now if you click on the About or Contact page, nothing will
happen. The next thing we want to do is that when the About and Contact buttons are clicked,
it should show the value of the pages. I'm going to create a variable called pageRef and
reference the the attribute to href. The (this) in the code below is referenced to the a (anchor
element) and I'm going to call that function and then reference the URL like such

$(document).ready(function(){
16

$('a').on('click', function(e){
e.preventDefault( );
var pageRef = $(this).attr('href');

callPage(pageRef)

});

Save it, refresh the screen and now if you click on the About button, the information shows
without loading the entire page or going to another page.
17

I hope you enjoyed this lesson, if you have any question, leave your comments below. I'll talk
to you in the next lesson. Goodbye :)

You might also like