MC Press Online

Saturday, Jun 24th

Last updateFri, 23 Jun 2017 1pm

You are here: Home ARTICLES Programming Web Languages TechTip: jQuery Fundamentals, Part III

Programming / Web Languages

TechTip: jQuery Fundamentals, Part III

Support MC Press - Visit Our Sponsors

NEW BOOK!

Flexible Input, Dazzling Output with IBM i


ORDER YOUR COPY

*******************

Click for this Month's

Bookstore Special Deals

In this installment, callback functions are revealed.

 

In this third TechTip about jQuery fundamentals, I'll focus on a very powerful function that is available in a lot of the jQuery APIs: the callback function. To understand the callback paradigm on a simple level, you must first understand how a browser executes JavaScript. I'll explain that by making a comparison to RPG.

 

When you execute a series of subroutines in RPG, they're executed one by one, like so:

 

ExSr subr01

ExSr subr02

ExSr subr03

 

Here, you always know that subr03 is not executed before subr01 and subr02 are done, and subr02 is not executed before subr01 is done. This is very nice because if subr03 is depending on a result done in surb01, we always know that when subr03 is executed, the result from subr01 is ready for us. You can call this synchronous execution.

 

But JavaScript is different; it's executed asynchronously. If we follow the RPG example, it would mean that subr01, subr02, and subr03 are processed at the same time: asynchronous execution. Because you have no control over the process, this means that, in theory, subr03 could be executed before subr01, so you cannot be sure that the result from subr01 will be available for you in subr03, which can cause unpredictable results.

 

So, ladies and gentlemen, this is where jQuery callback functions kick in. So please pour yourself a cup of coffee or tea, put on an Elvis Costello record, and sit back and enjoy this little trip into the world of jQuery.

jQuery Callback Functions

A callback function is executed after the current function is 100% finished. This is just what we need in order to control a series of events that might depend on each other.

 

The syntax for a callback function is like this:

 

$("#myButton1").click(function() {

      $("#messagewindow").slideDown('slow',function() {

            alert('Window is visible');

});

});  

 

In the example, a click is attached to a button. When the button is clicked, a message window will slowly slide down and show an alert. If we didn't put the alert inside the callback function, the alert would be displayed long before the slide effect had finished.

An AJAX Example

Armed with our new knowledge of callback functions, let's make an example that shows how an AJAX call uses a callback function to process the returned data. Here's how the program works:

 

  1. 1.The program makes an AJAX function, getData(), that sends back the current PHP version and also the Unix Epoch time in seconds. The data is written into the div tag with id=data. (The Epoch time or POSIX time is the time since January 1, 1970 UTC midnight and is used in many operating systems and file systems to represent date and time.)
  2. 2.Function showData() will retrieve the content from the div tag with id=data and from the input field with id=epoch. The number in seconds from the input tag will be divided by 60 to see the representation in minutes and will be written to the div tag with id=data1. Of course this is a very simple and not very useful program, but the idea is to make you understand the callback function.
  3. 3.When we do not use the callback function, the calculation will fail and you will see that the result will be 'NaN' which means "Not a Number."

 

Below are some fragments of the program that, to me, are the most interesting. Let's look at what happens in the code.

 

//=========================================================================

// Page loaded

//=========================================================================

$(document).ready(function() {

      

       // Add click to button

       $("#button1").click(function() {

             getData();

             showData();

       });                

      

       // Add click to button

       $("#button2").click(function() {

             getDataWithCallBack();

       });                       

 

});   

//=========================================================================

 

 

Here, we add a click to the two buttons named button1 and button2. Note that in the click function for button1, the getData and showData functions are called repeatedly as in the RPG subroutine example. This will result in the NaN result from the AJAX call because the showData function will try to retrieve the data from the div tag before the getData function has finished its job and actually written the data to the div tag.

 

But in the button2 click, a function called getDataWithCallBack is called. In this function, a callback function is used, which will assure that all data are where we want them to be when the calculations occur.

 

Below are the functions to the AJAX call and the calculation function. I have added some comments that explain where important things happen, so pay attention to that code.

 

//=========================================================================

// Get data

//=========================================================================

function getData( ) {

 

       // Hide and set default

       $('#data').html('Working')

       $('#showdata').hide('fast')

 

 

       $.ajax({

             type: "GET",

             url: 'ex2-return-data.php',

             dataType: 'html',

             cache: false,             

             success: function( dataStream ) {

 

a) ? Show the data square and write the result to the div tag using a callback function

                    // Show data

                    $('#showdata').show('fast',function() {

                           $('#data').html(dataStream)

                    });                

 

             },

                    error:function (xhr, ajaxOptions, thrownError){            

                   

                    // Error handling goes here...

 

             }

            

       });

      

}

 

//======================================================================================

// Get data with call back

//======================================================================================

function getDataWithCallBack( ) {

 

       // Hide and set default

       $('#data').html('Working')

       $('#showdata').hide('fast')

 

 

       $.ajax({

             type: "GET",

             url: 'ex2-return-data.php',

             dataType: 'html',

             cache: false,             

             success: function( dataStream ) {

 

 

            

                    // Write data to div

 

b) ? Write data to the data div tag

                    $('#data').html( dataStream );

                   

c) ? Show the data square and call the calculation function when you know the data is in place

                    // Show data

                    $('#showdata').show('fast',function() {

                           showData();

                    });                

            

 

             },

                    error:function (xhr, ajaxOptions, thrownError){            

                   

                    // Error handling goes here...

 

             },

            

d) ? You could also use the "complete" callback function in the ajax call to gain the same result as in the "success" callback function

 

                    complete:function ( dataStream ){      

            

                    // // When done - this call back could also be used

                    // $('#showdata').show('fast',function() {

                           // $('#data').html(dataStream)

                    // });             

                   

             }           

                   

       });

      

}

//======================================================================================

// Get data

//======================================================================================

function showData( ) {

 

e) ? Get the epoch number, calculate and write the result to the data1 div tag

       var number = $('#epoch').val()

       var minutes = parseInt( number / 60 );

       $('#data1').text( 'Minutes since Epoch: ' + minutes );

 

}

 

 

When not using the callback function (button1), the result will be as shown in Figure 1, and when using the callback function (button2), the result will be as in Figure 2.

 

030813JorgensenFig1                       

Figure 1: Here, the code is called without the callback function.

 

030813JorgensenFig2 

Figure 2: Here, the code is called with the callback function.

 

Let's Call It a Day

Well, that completes this TechTip. I really hope you can see the value of this powerful feature, which is just another wonderful part of the jQuery library.

 

You can download all the examples from this link.

 

I have also, as I always do, uploaded the examples to my own website, where you can see the examples in real life.

 

Example showing the basic use of callback using an alert:

http://agnethe.dk/mcpressonline/jquery_fundamentals_part3/ex1.htm

 

Example showing the calculation with and without the use of callback functions:

http://agnethe.dk/mcpressonline/jquery_fundamentals_part3/ex2.php

 

In the next part of the jQuery fundamentals TechTip series, I will create a program using jQuery, PHP, and RPG that will let you monitor whether a user is online on your i5 system. I hope it will be an inspire you toward further jQuery development. You might also like to review the first and second parts of this series.

 

Till next time, happy jQuery'ing and don't forget to "callback."

 

Jan Jorgensen

Jan Jorgensen is one of the owners of www.reeft.dk, which specializes in mobile and i5 solutions. He works with RPG, HTML, JavaScript, Perl, and PHP. You can reach him at jj@reeft.dk

 

BLOG COMMENTS POWERED BY DISQUS