Tuesday, 19 July 2011

Ajax-jQuery: Basics

Ajax was known as Asynchornous Javascript and XML. But now, it is known as any technique or
technology that lets a user's browser interact with a server without disturbing the existing page.
For example, in gmail, part of the page is loaded without changing the page, like the inbox.

1. load
    
   $('div:first').load('test.html');
   
This dynamically inserts the entire contents of the test.html file into the first div on the current page.

   $('#container').load('test.html' '#wrap'); //Insert the element with an id of wrap from test.htmlt
                                           to element with an id of container in current page.

  Note: Even though only selected elements are displayed, the whole page is loaded first. Then, the
        selected elements are displayed. So no performance benefits there.


  A callback function can also be inserted after the path of the page
  eg: $('# ').load('test.html function(faas, asdf){});

2. live, die
    Suppose we are trying to change the propery of an element that is being loaded from another page, it might not work properly
    since the element might not be loaded before the property is being changed. In order to avoid this problem, 'live' is used.

    
    live binds a handler to all CURRENT and FUTURE elements that matches.
    eg: $('#div').live('mouseover',function(){
        $(this).css( "background", "blue")               

             });

   When this is no more needed, die can be used.  $('div).die('mouseover');
3. $.getJSON()
   Note::  getJSON doesn't load the data directly to the DOM hence, it is represented by $.getJSON, not $('#df').getJSON.

   syntax: 

$.getJSON(url,[data],[success(data, textStatus, jqXHR) ] )
           url- URL of the file to be download
           [data]- data that is passed to the server
           callback function that is returned if the file is recieved successfully.

  $.getJSON passes parameters in GET method. POSTing is not possible with $.getJSON.
  $.getJSON treats response as JSON. 
3.$.GET() and $.POST()
   $.get(url, data, callback, dataType);
   $.post(url, data, callback, dataType);
4. $.ajax()
   More complex but provides greater functionality. It is the base for all the other Ajax functions in jQuery.
   
   $.ajax({
        type: 'GET',
        url: 'getDetails.php',
        data: { id: 142 },
        success: function(data) {
                // grabbed some data!
                    };
    });
  It provides the option of returning an error message in case it fails. 

No comments:

Post a Comment