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

Leave a Reply

Your email address will not be published. Required fields are marked *