To .get() and To .post() - An Intermediate Tutorial

January 27, 2011 — The .get() and .post() functions of jQuery let you load pages without refreshing a webpage. This article explains the extra parameters of the .get() and .post() methods and how to extend their use; it also assumes a basic understanding of jQuery.

.get() or .post() – Advanced

These two functions do more than pass variables silently to a webpage. They can also pass multiple arrays, perform functions after successfully loading a webpage, and retrieve and use the output of a page.

.get() or .post() Sending Arrays

We can pass a single array to pagetoload.php, or several arrays, and even a serialized array.

All of these will process pagetoload.html, and pass array variables
  1. $.get('pagetoload.php', {'pageData[]': ['519', currentPage]});
  1. $.get('pagetoload.php', {'pageData[]': [pageID, 'en-US'], 'itemData[]': [itemID, itemCode]});
  1. var formVars = $('FORM').serialize(); // Convert array of the form data into a string
    $.get('pagetoload.php', {name: formVars});

.get() or .post() Responding to Success

So far, all of these examples are hidden; they don't notify you nor the user that something has happened. To do that, we'll need to use a "callback function". A callback function is merely a function that starts working after the parent function finishes. Simply write a function where you would normally place a paramater:

All of these will process pagetoload.html, and then alert us the page was successfully loaded
  1. $.get('pagetoload.php', alert('The page was loaded!'));
  1. $.get('pagetoload.php', function(){
  2.     $('.successMessage').text('Operation Complete'); // Update text of .successMessage
  3. });
  1. function removeProductRow(){
  2.     $('#product'+productID).remove(); // Remove a product from the screen
  3.     $('.successMessage').show(); // Display the .successMessage
  4. }
  5. $.get('pagetoload.php', function(){
  6.     $('.successMessage').text('Operation Complete'); // Update text of .successMessage
  7.     removeProductRow();
  8. });

.get() or .post() Using the Output

The callback function can take paramaters also, three to be exact. For this tutorial, we'll mention just the first one, data. If we pass the parameter data, we can then use the data variable, which contains the output of the page. If this output is HTML, for example, we could load it into a [div].

Both of these will process pagetoload.html, and load the content of pagetoload.php into #myDynamicDiv
Only the $.get() function will also alert us the page was loaded
  1. $.get('pagetoload.php', function(data){
  2.     $('#myDynamicDiv').html(data); // Load data into a <div> as HTML
  3.     alert('The page was loaded!');
  4. });
  1. $('#myDynamicDiv').load('pagetoload.php');

Add a Comment


Posted Subject Comment
Please be the first to submit a comment.