Tutorials JavaScript AJAX Content

AJAX Content

Have you ever been to a website that offers "real-time" content updates? Google Maps only loads the part of the map you're looking at so you don't load the entire world. Twitter notifies you of new tweets as you're reading. Facebook has a chatroom that updates witout refreshing the page. They are using AJAX to reload content without refreshing the page.

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It allows the browser to communicate with the server without refreshing the page. You can send forms or update content without a full page reload.

Loading new pages with AJAX

You can use jQuery's load function to grab data from another page. This will grab the new content and put it in the selected container.

$('#content').load('about.html .content-inner');

Animating content with AJAX

If you're going to just click on and off, you might as well just let your users load a new page. Sometimes you want to add some animations to your content. The function has a callback once it finishes loading so you can easily animate in and out.

$('#content').animate({
  opacity: 0
}, 500, 'swing', function() {
  
  // load new content
  $('#content').load('about.html .content-inner', function() {
    // load successful
    
    // fade in new content
    $('#content').animate({
      opacity: 1
    }, 500, 'swing');
      
  }); // end content load
  
});// end fade out

Demo: http://www.phptrainee.com/files/ajax-content/index.html

Should I use AJAX?

Making a website in AJAX is a lot more work. JavaScript binds functions to objects on the page so if your website uses a lot of JavaScript, it becomes hard to differentiate changes and you often forget to rebind functions. If you decide to use AJAX, be prepared to double or triple your development time for QA testing. Sometimes it is better to do a simple trick perfectly than to attempt a difficult trick and blunder it.

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.