Categories
JavaScript

JQuery and Ajax

$('#headlines').load('todays_news.html'); // Loads the html page into the headlines DOM element

The limitation of the method above is that  the page loaded has to be from the same server / domain.

If you want to load only an specific part of the requested page, you can access only that part by id (say id is ‘news’):

$('#headlines').load('todays_news.html #news');

In JQuery, the way to specify GET and POST commands is as follows:

$.get(url, data, callback);  // or  $.get(‘rateMovie.php’,’rating=5′);

$.post(url, data, callback); // or $.post('rateMovie.php','rating=5&user=Bob');

Just remember that when preparing the data,  you have to url encode some of the arguments:

encodeURIComponent(‘Mac & Cheese’);

If you want to include all the elements of a form at once when you send your request, you can use the serialize() function to do so (say your form id is #login):

var formData = $('#login').serialize();
$.get('login.php',formData,loginResults);

This is a typical callback function:

function processResponse(data, status) {
     var newHTML;
     if (status==’success’) {
       newHTML = ‘<h2>Your vote is counted</h2>’;
       newHTML += ‘<p>The average rating for this movie is ‘;
       newHTML += data + ‘.</p>’;
     } else {
       newHTML='<h2>There has been an error.</h2>’;
       newHTML+='<p>Please try again later.</p>’;
     }
     $(‘#message’).html(newHTML);
   }

The callback function could also be specified as an anonymous function:

.get('file.php', data, function(data,status) {
   // callback function programming goes here
});

If you received XML content back from the server, you can parse it this way:

$.get(‘xml.php’,’id=234′,processXML);
function processXML(data) {
  var messageContent=$(data).find(‘content’).text();
}

In this example, the actual XML received may look like:

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<message id=”234″>
  <from>Bob</from>
  <to>Janette</to>
  <subject>Hi Janette</subject>
  <content>Janette, let’s grab lunch today.</content>
</message>

In order to convert the response to a JSON object usable by JavaScript directly, you can use the following:

$.getJSON(‘contacts.php’,’contact=123′,processContacts); // same as $.get(), but the ‘data’ variable is a JSON object instead of text

If you need to loop through a JSON object, you can use the JQuery $.each() function.

Say that you have the following object coming back from the server:

var data = {
  contact1: {
    firstName: 'Frank',
    lastName: 'Smith',
    phone: '503-555-1212'
  },
  contact2: {
    firstName: 'Peggy',
    lastName: 'Jones',
    phone: '415-555-5235'
  }
};

The following callback function can be used to parse it:

   $.getJSON(‘contacts.php’,’limit=2′,processContacts);
   function processContacts(data) {
     // create variable with empty string
     var infoHTML=”;

     //loop through each object in the JSON data
     $.each(data,function(contact, contactInfo) {
         infoHTML+='<p>Contact: ‘ + contactInfo.firstName;
         infoHTML+=’ ‘ + contactInfo.lastName + ‘<br>’;
         infoHTML+=’Phone: ‘ + contactInfo.phone + ‘</p>’;
     }); // end of each()

     // add finished HTML to page
     $(‘#info’).html(infoHTML);
   }

In that case, the argument ‘contact’ will point to ‘contact1’ and ‘contact2’, and the contactInfo to the information on each of those sub-objects

Categories
JavaScript

Ajax

XMLHttpRequest object: is a browser object that allows you to communicate to the server. To create one of these objects you use the following JavaScript code:

var newXHR = new XMLHttpRequest(); // Doesn’t work in IE 6 though

In order to send a GET request using the object above, you do something like:

newXHR.open(‘GET’, ‘shop.php?productID=34’);

To indicate the callback function that will process the request received back from the server:

newXHR.onreadystatechange = myCallbackFunction;

Up to this point, everything has been setup, now to send the data to the server you use:

newXHR.send(null);

If you want to send additional parameters, instead of null you specify:

newXHR.send('q=javascript');

The XHR object receives up to three pieces of information back from the server:

  • status: like 404, 500, 200, etc
  • responseText property: it is part of the XHR object, and stores the server response, could be HTML, plain text, or a JSON object
  • responseXML property: also part of the XHR object. Loaded if the server responds with XML
Categories
JavaScript

Ajax

  • asynchronous javascript and xml
  • Disadvantages:
    • Depends on JS to be turned on
    • Difficult to maintain a clear separation between presentation and logic layers, may be difficult to debug
    • Search engines will not be able to access ajax based data
  • The five status of ajax return call code: 5 readyStates0 = uninitialized1 = loading2 = loaded3 = interactive4 = complete
  • Ajax polling methods:
    • HTTP pull: Client constantly and periodically ping the server for data
    • COMET / Bauyer approach: the server side runs in a self loop for a given period of time (usually 45 secs), if any new event occurs in that time, it is sent to the client. If not, the client at the end reopens another 45 secs loop.