Saturday, May 4, 2013

Create Your First Website :- Tutorial-3(d) on JavaScript

Lesson 18: Making AJAX Calls

One core feature of 21st century web applications is their fantastic responsiveness. A pioneer in the business of making the web more and more similar to a desktop application has been Google: as soon as you start typing a character in a Google box, all kinds of suggestions and search results keep popping up to speed up your search; and again, just type something using Google maps, and you're instantly catapulted to almost any street on the planet.
Behind this amazing feat of human cleverness is the coming together of a few technologies collectively known as AJAX.
In this lesson you will learn:
  • what AJAX stands for and what it is all about;
  • how to make an AJAX request;
  • how to handle an AJAX response.
I recommend you get access to a web server to carry out the example code illustrated in this lesson. In fact, AJAX is all about client-server communication. In view of this, you can upload your files to a hosted server or to a local server.

What's AJAX all about?

The acronym AJAX stands for Asynchronous JavaScript And XML.
In actual fact, it's a combination of internet standards made up of:
  • standards-based presentation using HTML and CSS;
  • dynamic display using the DOM;
  • data interchange and manipulation using XML;
  • asynchronous data retrieval using the XMLHttpRequest object;
  • JavaScript magic to orchestrate the whole process.
In non-AJAX web applications, the interaction between servers and clients can be a tedious business:
  1. a user action from the client sends a request to the web server via HyperText Transfer Protocol (HTTP);
  2. the web server receives the request and processes it by invoking server-side scripts, database data, etc., and sends a response back to the client via HTTP;
  3. the client browser receives the response and loads the entire updated page.
Having to go from browser to server and back again each time a user requests some piece of data from the server, in addition to undergoing an entire page refresh at each update, can be quite stressful on servers and on users alike.
AJAX helps in at least 2 respects: piecemeal page updates and asynchronous communication between server and client.
What this means in a few words, is that every time the user interacts with the web page, only those bits that need updating are refreshed, not the entire page. Furthermore, the fact that AJAX operations are performed asynchronously, means that during the time that it takes for the server to respond, the page is not locked and the user can still interact with the website.

How do I make an AJAX request?

An AJAX request is made using the XMLHttpRequest object and its open() and send() methods. This is supported by all major browsers. However, older browsers, namely older varsions of Microsoft Internet Explorer (vesions 5 and 6), support an ActiveXObject. This little hurdle is easily overcome by testing for feature support in the script.
The open(retrievalMethod, url, bool) method has 3 arguments:
  1. retrievalMethod: this can either be a GET (used to fetch data from the server), or a POST (used to send data to the server);
  2. url: this is the location where the data is made available. It can be a text file, an XML document, or a server-side script that processes data coming from a database;
  3. bool: this is a true/false value. If it's false the request is made synchronously, if it's true the request is made asynchronously, which is what we usually want.
The XMLHttpRequest object has an onreadystatechange property that deals with the response from the server. This proceeds over the following 5 stages:
  • 0) the request is uninitialized because open() has not been called;
  • 1) the request is specified, but send() has not been called yet;
  • 2) the request is being sent, because now send() has been called;
  • 3) the response is being received, but not yet completed;
  • 4) the response is complete and data is available for manipulation and display.
Upon completion (stage 4), the XMLHttpRequest object's status property gets assigned an HTTP status code that describes the result of the request as follows:
  • 200: success!
  • 401: unauthorized - authentication is required and was not provided;
  • 403: forbidden - the server refuses to respond;
  • 404: not found - the requested resource cannot be found.
This is a simple code snippet that translates what's just been said into practice:
  //Global variable to store the XMLHttpRequest object
  
  var myRequest;
  
  //Package the request into its own function
  
  function getData()
  
  {
  
  //Feature-testing technique to make sure the browser
  
  //supports the XMLHttpRequest object
  
  if (window.XMLHttpRequest)
  
  {
  
  //create a new instance of the object
  
  myRequest = new XMLHttpRequest();
  
  }
  
  //else - the XMLHttpRequest object is not supported:
  
  //create an instance of ActiveXObject
  
  else
  
  {
  
  myRequest = new ActiveXObject("Microsoft.XMLHTTP");
  
  }
  
  //Use the open(retrievalMethod, "myDataFile.txt", bool) method
  
  myRequest.open("GET", url, true);
  
  //Use send() with a null argument - we have nothing to send:
  
  myRequest.send(null);
  
  //attach a function to handle onreadystatechange,
  
  //that is, the response from the server:
  
  myRequest.onreadystatechange = getData;
  
  }
  
  

How do I handle the AJAX response?

If the client browser requests text data, the server response is automatically stored in the responseText property.
If the client browser requests data in XML format, the server response is stored in the responseXML property.
Here's a code snippet that illustrates this in practice.
  //Package the response-handling code in a function
  
  function getData()
  
  {
  
  //Make sure the response is at the completion stage (4):
  
  if (myRequest.readyState ===4)
  
  {
  
  //if it is, make sure the status code is 200 (success):
  
  if (myRequest.status === 200)
  
  {
  
  //if all is well, handle the response:
  
  var text = myRequest.responseText;
  
  alert(text);
  
  }
  
  }
  
  }
  
  
Let's tackle two examples that include both request and response using AJAX. The first example will be dealing with a response in plain text format, the second example with a response in XML format.

AJAX request - response example: plain text response

To follow along, you need a server and 1 simple text file uploaded to the same server that hosts your JavaScript code.
The page you're going to build allows the user to click a button to display some text stored in your text file using AJAX.
Here's a simple HTML page with a <header> tag and a button element:
  <!DOCTYPE html>
  <html>
  <head>
  <title>Lesson 18: Making AJAX Calls</title>
  
  </head>
  <body>
  <h1>Lesson 18: Making AJAX Calls - Plain Text Response</h1>
  
  <div>
  
  <h2 id="myHeader">Click the button to call your data</h2>
  
  <input type="button" value="Click Me!" onclick="getText('lesson18_test.txt')" />
  
  </div>
  
  <script type="text/javascript">
  
  //JavaScript AJAX code here
  
  </script>
   
  </body>
  </html>
  
  
Here's the JavaScript code that goes in enclosing <script> tags in the HTML page above:
  //Prepare the global variable for the request
  
  var myRequest;
  
  //Write the getText(url) function
  
  function getText(url)
  
  {
  
  //check support for the XMLHttpRequest object
  
  if (window.XMLHttpRequest)
  
  {
  
  myRequest = new XMLHttpRequest();
  
  }
  
  //else, create an ActiveXObject for IE6
  
  else
  
  {
  
  myRequest = new ActiveXObject("Microsoft.XMLHTTP");
  
  }
  
  //Call the open() method to make the request
  
  myRequest.open("GET", url, true);
  
  //Send the request
  
  myRequest.send(null);
  
  //Assign the getData() function to the
  
  //onreadystatechange property to handle server response
  
  myRequest.onreadystatechange = getData;
  
  }
  
  
  
  /**********************************************/
  
  
  
  //This function handles the server response
  
  function getData()
  
  {
  
  //Get a reference to the header element where
  
  //the returned result will be displayed
  
  var myHeader = document.getElementById("myHeader");
  
  //Check the response is complete
  
  if (myRequest.readyState ===4)
  
  {
  
  //Check the status code of the response is successful
  
  if (myRequest.status === 200)
  
  {
  
  //Store the response
  
  var text = myRequest.responseText;
  
  //Assing the returned text to the nodeValue
  
  //property of the header element (you can also use
  
  //innerHTML here if you feel it simplifies your task)
  
  myHeader.firstChild.nodeValue = text;
  
  }
  
  }
  
  }
  
  
Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.
Notice how the result is returned from the server with no page flashing, no change of URL, no whole page refresh: that's the AJAX magic.

AJAX request - response example: XML format response

The page you're going to build in this second example allows the user to click a button to display a series of programming languages coming from an XML file using AJAX.
To follow along in this exercise, prepare a simple XML document and an HTML page.
Here's what my XML document looks like:
  <?xml version="1.0" ?>
  
  <languages>
   <language>PHP</language>
   <language>Ruby On Rails</language>
   <language>C#</language>
   <language>JavaScript</language>
  </languages>
  
  
Save the file above as lesson18_test.xml in the same location as your HTML page.
Here's the HTML page:
  <!DOCTYPE html>
  <html>
  <head>
  <title>Lesson 18: Making AJAX Calls</title>
  
  </head>
  <body>
  <h1>Lesson 18: Making AJAX Calls - XML Response</h1>
  
  <div id="test">
  
  <h2>Click the button to get a list of programming languages</h2>
  
  <input type="button" value="Click Me!" onclick="loadXml('lesson18_test.xml')" />
  
  </div>
  
  <script type="text/javascript">
  
  //JavaScript AJAX code here
  
  </script>
   
  </body>
  </html>
  
  
Now proceed with the JavaScript code as follows:
  var myRequest;
  
  //The greatest part of the loadXML() function
  
  //is similar to the previous example:
  
  function loadXML(url)
  
  {
  
  if (window.XMLHttpRequest)
  
  {
  
  myRequest = new XMLHttpRequest();
  
  }
  
  else
  
  {
  
  myRequest = new ActiveXObject("Microsoft.XMLHTTP");
  
  }
  
  myRequest.open("GET", url, true);
  
  myRequest.send(null);
  
  myRequest.onreadystatechange = getData; 
  
  }
   
  
  /******************************************/
  
  
  function getData()
  
  {
  
  //Get a reference to the div element
  
  //where the returned data will be displayed:
  
  var myDiv = document.getElementById("test");
  
  //The part of the code that checks the response
  
  //is the same as the previous example:
  
  if (myRequest.readyState ===4)
  
  {
  
  if (myRequest.status === 200)
  
  {
  
  //Use the responseXML property to catch
  
  //the returned data, select the xml tag
  
  //called language, and store returned
  
  //language items in an array variable:
  
  var languages = myRequest.responseXML.getElementsByTagName("language");
  
  //Loop over each array item containing the data
  
  //and create a <p> element to contain each returned
  
  //piece of data.  Notice the use of firstChild.data
  
  //to retrieve the value of the XML <language> tag:
  
  for (var i = 0; i < languages.length; i++)
  
  {
  
  var paragraph = document.createElement("p");
  
  myDiv.appendChild(paragraph);
  
  paragraph.appendChild(document.createTextNode(languages[i].firstChild.data));
  
  //You can also assign the returned result to myDiv.innerHTML
  
  //if you feel it would be simpler.
  
  }
  
  }
  
  }
  
  }
  
  
Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.
Notice how the result is returned from the server without a whole page refresh. That's terrific!

Summary

That's it for this lesson. You worked really hard, but now you can write JavaScript code that retrieves data from the server without a whole page refresh using AJAX techniques.
You're not limited to text format files or to XML files, though. In fact, databases are the most commonly used tools to permanently store data on a server. AJAX techniques are as easily applied to deal with database retrieved information. However, you'll need PHP or a server-side programming language to retrieve data from or post data to a database.

Lesson 19: Short Introduction to jQuery



You've come a long way in your JavaScript journey. Now it's time to get to the fun part.
This lesson, together with the next 2 lessons, will introduce you to jQuery, the fantastic JavaScript library invented by John Resig.
However, this is a wide topic and these 3 lessons cannot but give you just a taste for what jQuery can really do.
Therefore, I encourage you to visit the jQuery website after you finish this tutorial, and explore and experiment with jQuery's numerous methods, events, effects, etc., for yourself.
In this lesson you will learn:
  • about the benefits of using jQuery;
  • how to include jQuery in your project;
  • about jQuery selectors to manipulate DOM elements in code;
  • how jQuery handles events;
  • how to use anonymous functions with jQuery;
  • how to add and remove DOM elements with jQuery.

Why should I use jQuery?

Here are some good reasons why using jQuery in your JavaScript projects is a great idea.
jQuery is:
  • extremely light-weight (just 31 kb in its latest minified and zipped production-ready version);
  • it's free and very easy to include in your projects: just download its latest version from the jQuery website, or use an online Content Delivery Network;
  • it's continually upgraded, maintained and documented by a dedicated community of great developers. This ensures high quality and support on the internet;
  • it helps overcoming inconsistencies in the way some JavaScript features are implemented across different browsers;
  • and last but not least, it offers a wealth of ready-made animation effects that are a joy to use.

How do I include jQuery in my website?

Including jQuery in your project is fast and easy. You have the choice of downloading a copy of the library and save it locally, or you can use a Content Delivery Network (CDN) to serve jQuery to your website on the Internet.
Go to the jQuery website download page

How to include a local copy of jQuery

If you prefer having a local copy of jQuery:
  1. go to the Download jQuery section of the download page and click on the minified version of the latest release of jQuery. At the time of writing this is version 1.7;
  2. copy and paste the code in a text file;
  3. save the file in your web project directory (better if you save it in its own subfolder);
  4. in your html page include the appropriate <script> tags in the following order:
  <!DOCTYPE html>
  <html>
  <head>
  <title>Lesson 19: Introduction to jQuery</title>
  
  <script type="text/javascript" src="js/latestjquery.js"></script>
  
  <script type="text/javascript" src="js/yourscript.js"></script>
  
  </head>
  <body>
  <h1>Lesson 19: Introduction to jQuery</h1>
   
  </body>
  </html>
  
  
The reference to jQuery comes before your own JavaScript code file. In fact, your code needs to find jQuery already fully loaded to be able to use it.

How to include a hosted copy of jQuery

If you decide to opt for a CDN to serve up a copy of jQuery to your website, then follow these easy steps:
  1. go to the CDN Hosted jQuery section of the download page and pick one of the different CDN services available;
  2. copy the URL of your CDN of choice and paste it as the value of the <script> tag's src attribute, like so:
    <script type="text/javascript" src"yourCDNUrlAddressjQueryFile.js"></script>
  3. place a <script> tag with a reference to your own JavaScript file underneath the jQuery <script> tag, like you did in the previous example.
That's it, you're done!

How to make sure jQuery is working

Now the jQuery library can be used in your project. To make sure things work as expected, create a text file and call it jquery_test.js. Enter the following code:
  //Most of your code goes inside
  
  //the jQuery ready() function:
  
  $(document).ready(function()
  
  {
  
  alert("jQuery is working!");
  
  });
  
  //Make sure you keep track of braces, brackets, and semi-colons ( ; )
  
  
Save all your files and run the HTML page in a browser. If you typed the code exactly like the example above, you should be greeted by ... well, the good old alert box.
The $ sign is an alias for jQuery. You could replace it with the keyword jQuery and your jQuery-powered JavaScript code would work just fine. However, less typing is jQuery's (and all coders') motto, so using $ is the accepted convention.
.ready(function() { //JavaScript code here ... } );
is where most of your JavaScript code will be placed. This is jQuery's clever way of making sure your code runs when the document is ready for it: that is, when the html is fully loaded.

How do I access DOM elements using jQuery?

jQuery appeals so much to web designers also because it enables us to select DOM elements in code just like we do with CSS. Let's see it in action.

Select html elements by id

Remember our old document.getElementById()? Well, jQuery makes selection by id much shorter. Here's how it's done:
  $(document).ready(function()
  
  {
  
  var myDiv = $("#myDiv");
  
  });
  
  
The $ sign in front of ("#myDiv") can be translated like: "Hey, browser, get me the element with the id of myDiv!"
As you can see, the id attribute is grabbed by using the # sign, the same as CSS.

Select html elements by tag name

You also came across document.getElementsByTagName(). This method allows us to grab all html elements by their tag.
Look how jQuery makes it a lot snappier:
  $(document).ready(function)
  
  {
  
  //store all images on the page in an array
  
  var images = $("img");
  
  });
  
  
As you can see, the magic $ does most of the talking.

Select html elements by class name

A quick way to target html elements that share the same class is as follows:
  $(document).ready(function()
  
  {
  
  var redElements = $(".classRed");
  
  });
  
  
Now redElements contains an array of all the html elements on your page with a class of classRed.
Once again, notice how jQuery facilitates selection by using the same notation you use in your CSS declarations to target classes: .className.

Select html elements using jQuery filters

jQuery enables you to be as precise as a surgeon when targeting html elements and attributes on the page. jQuery offers a filtering syntax to query the DOM that is both simple and efficient.
Here's a list of the most common filters:
Filter Description
:first The first item in a matched set
$(‘p:first’) returns the first paragraph.
:last The last item in a matched set
$(‘p:last’) returns the last paragraph.
:odd The odd-indexed items in a matched set
$(‘tr:odd’) returns table rows indexed at 1, 3, etc.
:even The even-indexed items in a matched set
$(‘tr:even’) returns table rows indexed at 0, 2, etc.
:has finds elements having the child element specified
$(‘p:has(span)’) returns all paragraphs containing a span element.
:eq returns the element with the matched index
$(‘p:eq(1)’) returns the second paragraph starting to count at 0.
:contains(x) Returns all elements containing the text x
$(‘div:contains(foo)’) targets all divs with the text 'foo'.
A complete list of all selection methods and filters is available on the jQuery website. Have a look and experiment with the available code samples to gain more familiarity with the new approach.

How do I assign event handlers using jQuery?

Event handlers are code blocks, usually functions, that specify what your application should do when a specified event like, for example, a button click, occurs.
So far, you've used 2 approaches:
  1. hard-wiring a function to the html element itself: <input type="button" onclick="doSomething()" />
  2. assigning a function to the DOM object's appropriate property: myElement.onclick = doSomething;
Both approaches are fine. However, the first one sins against the separation of concerns principle. In fact, it mixes in JavaScript code with HTML code.
The second approach complies with the separation of concerns principles, but comes short in case we want to attach more than a function to the same element.
There's actually a third approach that overcomes all shortcomings but one: it's implemented differently in Internet Explorer browsers with respect to all other major browsers.
The good news is: jQuery is here to make event handling quick and easy. Here are a few jQuery approaches to choose from.

The bind() method

bind(eventType, handler) works as follows.
Suppose you have an html element with an id of myElement, and a function called sayHello(). You want sayHello() to kick in when the user clicks on the html element. This is how you achieve this using bind():
  $(document).ready(function()
  
  {
  
  //create the sayHello function
  
  function sayHello()
  
  {
  
  alert("Hello jQuery");
  
  }
  
  //Attach the handler using .bind():
  
  myElement.bind('click', sayHello);
  
  });
  
  
You can find more details on the bind() method on http://api.jquery.com/bind/.

The ready-made approach

jQuery offers some ready-made handlers corresponding to JavaScript events. Here's a list of the most widely used ones:
Handler Description
click() Binds a handler to an onclick event.
hover() Binds a handler to the onmouseover and onmouseout events.
change() Binds a handler to the onchange event (when the content of a field changes).
select() Binds a handler to the onselect event (when text is selected).
submit() Binds a handler to the onsubmit event of a form element.
focus() Binds a handler to the onfocus event (when an element gets focus).
keypress() Binds a handler to the onkeypress event (when a key on the computer keyboard is pressed).
Assuming you have an html element with an id attribute of myElement, and a function called sayHello() - as in the previous example - you can bind sayHello() to the onclick event of myElement inside jQuery's ready() function like so:
  myElement.click(sayHello);
  
  

The on() method

With this latest version of jQuery (v.1.7), a brand new method to handle events has been introduced.
The on() method is highly recommended by the jQuery team if you start a new project.
It can be used to attach handlers both to elements already present in the HTML page from the start and on dynamically added elements (unlike bind()). Here's how it's used.
Using the same sayHello() function, inside jQuery's .ready() function simply write:
  myElement.on('click', sayHello);
  
  
More details on the on() method can be found on http://api.jquery.com/on/.

Anonymous functions

Code samples using jQuery often employ anonymous functions. These are functions without a name, and can be quite handy, although I find names more helpful in terms of code readability. If we replace the sayHello() function with an anonymous function, we have:
  //Using bind():
  
  myElement.bind('click', function()
  
  {
  
  alert("Hello jQuery");
  
  });
  
  
  
  /********************************/
  
  
  
  //Using click(), we have:
  
  myElement.click(function()
  
  {
  
  alert("Hello jQuery");
  
  });
  
  
  
  /**************************************/
  
  
  
  //Using on(), we have:
  
  myElement.on('click', function()
  
  {
  
  alert("Hello jQuery");
  
  });
  
  

Add and remove DOM elements

Once grabbed by your JavaScript code, DOM elements can easily be manipulated with jQuery.
You've had a taste of standards-compliant DOM manipulation techniques in this tutorial. Therefore, you will readily appreciate the jQuery way of performing the same tasks.

Add new DOM elements

You can both retrieve html elements and add new html elements to the page using jQuery's .html() method. When you don't pass any arguments, html() retrieves a DOM element, if you pass a string argument, html() adds that string to the page.
If you just need to add new text inside an html element, you can use jQuery's .text() method and pass a string argument representing the text you intend to add. Like .html(), you can use .text() without passing any arguments to retrieve text content from the HTML page.
To test .html() prepare an HTML page containing a <div> tag with an id of myElement, a <p> tag and some text. First we retrieve the existing paragraph element, then we create a new paragraph.
  $(document).ready(function()
  
  {
  
  //Use html() to retrieve content:
  
  var pageParagraph = $('p').html();
  
  //the alert should display <p>'s content
  
  alert(pageParagraph);
  
  });
  
  
  /**************************************************/
  
  
  //Now let's change the div's content
  
  //by adding a new paragraph.
  
  var newParagraph = $('#myElement').html('<p>Hello new Paragraph!</p>');
  
  //close off all your brackets:
  
  });
  
  
Save all your files and preview the result in a browser. The alert should display the original paragraph's content, and the page should subsequently display the new paragraph's content.
The way you implement .text() is the same as .html(). I leave you to experiment with it on your own. More details on .html() can be found on http://api.jquery.com/html/, and on .text() can be found on http://api.jquery.com/text/.

Remove DOM elements

A simple way of doing this is with jQuery's remove() method. Let's put it to the test.
Use the same HTML page from the previous example and add a button element with an id of btnDelete.
In a fresh JavaScript file, add the following code:
  $(document).ready(function()
  
  {
  
  //use a click handler and an anonymous function
  
  //to do the job
  
  $('#btnDelete').click(function()
  
  {
  
  //delete all <p> elements
  
  $('p').remove();
  
  });
  
  });
  
  
Save all your files and preview the HTML page in a browser. Click the button and see the paragraphs on the page disappear.
More on .remove() can be found on http://api.jquery.com/remove/.

Summary

There's a lot to digest in this introduction to jQuery and you've done a great job coming as far as you did.
jQuery is such a rich library that it can't be covered in a few lessons. Therefore, I invite you to practice with all the code samples in this lesson and the following lessons as much as you can.

Lesson 20: Cool Animation Effects with jQuery



jQuery is so rich with ready-made functions that adding fancy effects on your web page is a breeze. It's hard not to get carried away with it.
Here, we are going to explore the most commonly used jQuery effects. Once again, my recommendation is that of integrating this lesson with a visit to the jQuery website for more code samples and detailed explanations.
In this lesson you will learn how to:
  • add effects by dynamically manipulating styles;
  • use jQuery's show()/hide()/toggle() methods;
  • use jQuery's fadeIn()/fadeOut()/fadeToggle() methods;
  • use jQuery's slideUp()/slideDown()/slideToggle() methods.
In the process, you will build a simple sliding menu and get more practice with the new jQuery approach.

How do I add and remove CSS classes with jQuery?

jQuery enables you to manipulate CSS styles in code with $.css(styleName, styleValue). It also enables you to add and remove CSS classes in relation to DOM elements.
Because $.css() would sprinkle your HTML page with inline CSS style rules, we will focus on applying and removing CSS classes with $.addClass(className), $.removeClass(className), and $.toggleClass(className). This approach uses the CSS class declarations stored either in the <head> of your HTML page or in a separate file, therefore it's better suited to current best practices in web design.
If you're curious about $.css(), by all means visit http://api.jquery.com/css/ for more details.
Suppose you want to replace the CSS class bigDiv with the CSS class smallDiv when the user clicks inside the div element. This is how you could do the task with jQuery:
  $(document).ready(function()
  
  {
  
  //Store a reference to the div in a variable using its id:
  
  var myDiv = $('#myDiv');
  
  //Attach a click handler to manipulate the CSS classes:
  
  myDiv.click(function()
  
  {
  
  //Remove the existing CSS class and replace it with the new one.
  
  //Because the element is the same, chain both methods:
  
  myDiv.removeClass('bigDiv').addClass('smallDiv');
  
  });
  
  });
  
  
What about toggling between the CSS bigDiv and smallDiv classes by clicking inside the div? That's easy: jQuery has this little handy method for you - $.toggleClass(). Assuming the CSS class bigDiv is hard-coded in the class attribute of the div element, you can toggle the CSS class smallDiv using jQuery, like so:
  $(document).ready(function()
  
  {
  
  var myDiv = $('#myDiv');
  
  myDiv.click(function()
  
  {
  
  myDiv.toggleClass('smallDiv');
  
  });
  
  });
  
  
Now, keep clicking inside the div element, and you'll see it getting smaller and bigger at each click of the mouse.

How do I use jQuery show()/hide()?

If you want to show/hide HTML elements on a page, you can do so easily with jQuery's show()/hide(). You can also modulate the way elements are revealed or hidden by adding the 'slow' or 'fast' arguments, or even the number of milliseconds you'd like the transition to last.
Let's say you have a paragraph element inside a div with an id of myDiv. You want the paragraph to slowly disappear when the user clicks inside the div element. Here's how you could accomplish this with jQuery hide().
  $(document).ready(function()
  
  {
  
  var myDiv = $('#myDiv');
  
  myDiv.click(function()
  
  {
  
  //Replace 'slow' with 2000 for a slower transition.
  
  $('p').hide('slow');
  
  });
  
  });
  
  
Clicking inside the div element results in the paragraph slowly disappearing from view. jQuery show() works the same way. I leave you to experiment with it on your own.
What if you wanted to toggle between show/hide transitions as the user clicks inside the div element? No problem, jQuery offers the $.toggle() method. To see it in action, simply replace hide() with toggle() in the previous example, like so.
  $(document).ready(function()
  
  {
  
  var myDiv = $('#myDiv');
  
  myDiv.click(function()
  
  {
  
  $('p').toggle('slow');
  
  });
  
  });
  
  

How do I make DOM elements fade in and out of the page?

For a more sophisticated fading effect, use $.fadeIn()/$.fadeOut()/$.fadeToggle(). You use these methods the same way as you used $.show()/$.hide()/$.toggle() in the previous examples.
Here's the paragraph from the previous code sample toggling between visible and hidden using $.fadeToggle().
  $(document).ready(function()
  
  {
  
  var myDiv = $('#myDiv');
  
  myDiv.click(function()
  
  {
  
  $('p').fadeToggle('slow');
  
  });
  
  });
  
  
The effect is very similar to that of $.toggle('slow'). Just try it out.

How do I make DOM elements slide up and down with jQuery?

You can easily make DOM elements appear and disappear with a sliding effect using $.slideUp()/$.slideDown()/$.slideToggle(). You implement these methods similarly to the previous ones.
For example, let's say you want to slide the paragraph element from the previous example up and down as the user clicks inside the div element. Here's how you would accomplish this with $.slideToggle().
  $(document).ready(function()
  
  {
  
  var myDiv = $('#myDiv');
  
  myDiv.click(function()
  
  {
  
  $('p').slideToggle('slow');
  
  });
  
  });
  
  
Now keep clicking inside the div element and see the paragraph inside the div sliding up and down.
I recommend you experiment with the code samples above as much as you can before moving on with the next challenge.

Try out: sliding menu

Here we are at our jQuery try out exercise. You will build a simple sliding menu similar to what you might have already seen on many websites.
The user moves the mouse over a main menu item and a list of sub-menu items slides down. As the user moves the mouse away from the menu item, its sub-menu items slide back up away from view.
Let's start from the HTML page:
  <!DOCTYPE html>
  <html>
  <head>
  <title>Lesson 20: jQuery Sliding Menu</title>
  
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
  
  <script type="text/javascript" src="lesson20_ex.js"></script>
  
  </head>
  <body>
  <h1>Lesson 20: jQuery Sliding Menu</h1>
  
  <div id="myDiv">
  
  <ul class="outerList">
  <li><a href="#">Menu Item 1</a></li>
  <li><a href="#">Menu Item 2 ↓</a>
  
  <div>
  <ul class="innerList">
  <li><a href="#">Sub-Menu Item 1</a></li>
  <li><a href="#">Sub-Menu Item 2</a></li>
  <li><a href="#">Sub-Menu Item 3</a></li>
  </ul>
  </div>
  
  </li>
  <li><a href="#">Menu Item 3</a></li>
  </ul>
  
  </div>
   
  </body>
  </html>
  
  
The HTML page above has a reference to a CDN-served copy of jQuery and to an external JavaScript file in the <head> section.
The <body> section has a div element with an id of myDiv that contains a list with 3 main menu items and 3 sub-menu items nested inside the second main menu item. The sub-menu items are contained inside a div element.
Style your menu so that the main menu items are horizontally lined up and the nested sub-menu items are vertically stacked under their parent li element .
We want the div element that wraps the sub-menu items to slide down when the user moves the mouse over its parent li element.
Prepare your lesson24_ex.js file and write the following code.
  $(document).ready(function()
  
  {
  
  //retrieve the menu subitems (div element child of the list element)
  
  //with the powerful jQuery selectors
  
  //and store them in a variable
  
  var subItems = $('ul li div');
  
  //retrieve the main menu items that
  
  //have the retrieved subitems as children.
  
  //Notice the handy .has() method:
  
  var mainItems = $('ul li').has(subItems);
  
  //Hide all subitems on page load
  
  subItems.hide();
  
  //Attach the .hover() function to the main
  
  //menu items:
  
  $(mainItems).hover(function()
  
  {
  
  //Apply .slideToggle() to the sub-menu
  
  subItems.slideToggle('fast');
  
  });
  
  });
  
  
Save your work and preview it in a browser. You should see something like the page indicated by following the example link above, only reflecting your own CSS styles.
Move your mouse over the second menu item and if all goes as expected you'll see the sub-menu sliding down. It's taken us just a few lines of code to accomplish an animation effect that in raw JavaScript would have made us sweat quite a bit.

Summary

You've achieved a lot in this lesson. You know how to use several jQuery functions to manipulate styles. Also, you know how to add fancy effects to your web pages with very little code. Finally, you put your new knowledge to the test by building a core website component - a horizontal sliding menu - using jQuery.

Lesson 21: Easy AJAX Calls with jQuery



jQuery provides a rich set of handy methods you can use to Ajaxify your web pages.
Back in lesson 18 you used AJAX by dealing directly with the XMLHttpRequest object. You also performed some feature testing for Internet Explorer browsers that didn't support the XMLHttpRequest object.
jQuery provides wrapper methods that shield you from the inner mechanisms of an AJAX request.
In this lesson, you will learn how to use:
  • $.load() to request content from an HTML page;
  • the shorthand $.get() method;
  • the shorthand $.post() method;
  • the full-blown $.ajax() method.
To follow along with the examples in this lesson, you need to have access to a server, just as you did back in lesson 18.

How do I load HTML content with jQuery AJAX?

jQuery offers a very simple approach to loading HTML content on your web page asynchronously. Just use the $.load() function and you're done.
If you use $.load(htmlPageUrl) passing only the URL of the HTML document as argument, the entire content of the HTML document is loaded into the calling page.
Instead, I like to use $.load(htmlPageUrl fragmentIdentifier), which exactly targets the bit of content I intend to retrieve.
Here's how this is done in practice.
Prepare an HTML page containing a div element with an id of content and a paragraph element with some dummy content. Save it as content.html (or anything you like), and upload it to your server. This document provides the content to retrieve using AJAX.
Prepare a second HTML page containing a link element, a div element with an id of result, a reference to the jQuery library in the <head> section, and enclosing <script> tags in the <body> section for your own jQuery-powered JavaScript code.
  <!DOCTYPE html>
  <html>
  <head>
  <title>Lesson 21: Easy AJAX Calls with jQuery</title>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
  </head>
  <body>
  <h1>Lesson 21: Easy AJAX Calls with jQuery load()</h1>
  
  <p><a href="#">Click here to fetch HTML content</a></p>
  
  <div id="result">
  
  </div>
  
  <script type="text/javascript">
  
  //JavaScript AJAX code here
  
  </script>
   
  </body>
  </html>
  
  
For these simple demos, we're going to embed our JavaScript code inside the HTML page. However, keep in mind that, if you write code for a website, it's highly recommended that you use external JavaScript files.
When the user clicks on the link on your HTML page, an AJAX request will be made to content.html targeting the text inside the div element with an id of content. This text is dynamically inserted in the div with an id of result in the calling page.
To achieve this, enter the following code snippet inside the enclosing <script> tags:
  $(document).ready(function()
  
  {
  
  //Attach a handler to the click event
  
  //of the link on the page:
  
  $('a').click(function()
  
  {
  
  //Target the div with id of result
  
  //and load the content from the specified url
  
  //and the specified div element into it:
  
  $('#result').load('content.html #content');
  
  });
  
  });
  
  
Save your work and preview it in a browser. You should see something like the page indicated by following the example link above.
Click the link, and if all goes well, the dummy text from content.html is loaded inside the div element on the page. The operation takes place asynchronously without a full page refresh.

How do I use $.get()?

As nice and simple as $.load() is, it can't perform all types of content requests. A more flexible approach is offered by the $.get() method.
You can use $.get() to load data from the server with a GET HTTP request - that is, via a query string (see Lesson 10: Passing variables in a URL in the PHP tutorial on HTML.net for a great introduction to query strings).
$.get(url, {dataKey1 : 'dataValue1', dataKey2 : 'dataValue2'}, optionalSuccessFunction) takes in 3 arguments:
  1. theURL where the data you want to retrieve is stored;
  2. optionally, some data, if you want to send data to the server with the request. This is done using either a string or what is called object literal or map, that is, comma-separated key:value pairs inside curly braces. For instance: {'First Name' : 'John', 'Last Name' : 'Smith'} sends the First Name and Last Name values to the server together with the AJAX GET request;
  3. and a function that deals with the returned data if you want to display or process the successful response in any way.
Let's see how to use jQuery .get() to retrieve the XML document you used back in lesson 18.
The HTML page that makes the AJAX request remains unchanged from the previous example. Rewrite the JavaScript code as follows:
  $(document).ready(function()
  
  {
  
  //Store the URL value in a variable
  
  var url = "content.xml";
  
  
  /*************************************/
  
  
  //Package the result-handling code
  
  //in its own function: it's more readable
  
  function processData(data)
  
  {
  
  //This variable will hold the result
  
  //converted into a string for display
  
  var resultStr = "";
  
  //use jQuery .find() to extract the language
  
  //element from the returned data
  
  //and store it in an array
  
  var items = $(data).find('language');
  
  //loop over each language item with
  
  //jQuery .each() function
  
  $(items).each(function(i)
  
  {
  
  //extract the text of each language item and
  
  //add it to the resultStr variable with a line break.
  
  //Notice the use of $(this)
  
  //to refer to the item currently being
  
  //inspected by the loop
  
  resultStr += $(this).text() + '<br />';
  
  //add the final string result to div element
  
  //with the id of result using .html()
  
  $('#result').html(resultStr);
  
  });
  
  }
  
  
  /****************************************/
  
  
  //Attach a click handler to the link element:
  
  //when the user clicks on the link, the AJAX
  
  //request is sent to the server:
  
  $('a').click(function()
  
  {
  
  //use $.get() passing the url variable and
  
  //the name of the result-handling function
  
  //as arguments:
  
  $.get(url, processData);
  
  });
  
  });
  
  
Save all your files on the server and click on the link. If all goes well, you should see a list of programming languages being displayed on the page without a full page refresh.
In the example above, you came across jQuery .find() and jQuery .each().
$.find() is used to find a DOM element's descendants or children. In the example above, you used it to find all children called language of the root XML element contained in the variable called data. Further details on $.find() can be accessed on http://api.jquery.com/find/.
$.each(index) is a for ... loop done the jQuery way. It's extremely concise and efficient. Notice the use of $(this) inside the $.each() function block. This is a snappy way of referring to the item the loop is currently processing: in our example above $(this) refers to one of the language items in the items array.
More details on $.each() can be found on http://api.jquery.com/each/.

How do I use $.post()?

If you want to use POST instead of GET in your AJAX calls, you can use $.post().
Unlike GET requests, POST requests don't use a query string to send data. If you intend to send more than a few bits of data to the sever, or if you intend to send sensitive data, it's recommended you use an HTTP POST request.
The way you implement $.post() is very similar to the way you implemented $.get() in the previous example. I invite you to experiment with it on your own and to visit http://api.jquery.com/jQuery.post/ for more code samples and useful details.

How do I use $.ajax()?

If you need greater flexibility, the full-blown $.ajax() function offers a great number of settings.
For instance, let's say you want to retrieve a list of programming languages from the XML document you used in the previous example. You might want to specify the following options:
  1. the request must be an HTTP GET;
  2. the page from which the result is returned must not be in the browser's cache;
  3. the response returned by the server is of data-type XML;
  4. the request is made in html;
  5. there must be a function that handles the returned result if all goes well;
  6. and, finally, there must be a function that handles errors in case the request is not successful.
Use the HTML page and the XML document from the previous example. Also, keep the url variable and the processData() function from the previous exercise - you will use both as the url and the success arguments respectively inside the $.ajax() function. Delete everything else inside the document.ready() function. Just below the processData() function, write the following code:
  //Package the code that handles
  
  //error message in case the request
  
  //is not successful:
  
  function errorAlert(e, jqxhr)
  
  {
  
  alert("Your request was not successful: " + jqxhr);
  
  }
  
  
  /*************************************/
  
  
  //Attach a click handler to the
  
  //link element on the page
  
  $('a').click(function()
  
  {
  
  //Prepare the AJAX request that
  
  //will be sent when the user clicks the link:
  
  $.ajax(
  
  {
  
  type: "GET",
  
  cache: false,
  
  url: url,
  
  dataType: "xml",
  
  contentType: "text/html",
  
  success: processData,
  
  error: errorAlert
  
  }); //end of $.ajax
  
  }); //end of click handler
  
  });  //end of $.ready function
  
  
Save your work and preview it in a browser. The result should be similar to the previous example. If an error occurs, you'll be presented with an alert box. The errorAlert() function has an e argument that represents the type of error, and an jqxhr argument that represents the request as a jQuery object.
In case an error occurs, details about the error are automatically contained in the arguments provided and will be displayed in the alert box.
Do you want to test the error catching function? Simply replace dataType: "xml" in the $.ajax() function with dataType: "text/xml". Save all your files and run the HTML page. Now, when you click the link, an alert box should pop up displaying a parser error message.
More on $.ajax() can be found on http://api.jquery.com/jQuery.ajax/.

Summary

You got to the end of the lesson, and also to the end of this JavaScript tutorial. Congratulations!
Now you're familiar with the core JavaScript syntax and objects. You know how to include the jQuery library in your projects to add flair to your web pages and make AJAX calls easily and efficiently.