17
Sun, Nov
2 New Articles

TechTip: jQuery Fundamentals, Part III

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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 This email address is being protected from spambots. You need JavaScript enabled to view it.

 

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: