callback methods / anonymous functions: jQuery

Today lets see how callback methods or anonymous functions work. We also show you the anatomy of callback methods.

callback-method-anonymous-function-javascript-jquery-nodejs

callback methods are very important for achieving asynchronous way of coding.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !DOCTYPE html>
<html>
<head>
<title>callback or anonymous function</title>
<script src="jquery-1.10.2.min.js"></script>
<script src="myScript.js"></script>
</head>
<body>
 
<p></p>
<div></div>
 
</body>
</html>

Here we have included jQuery library and myScript.js We also have a paragraph tag and a div tag, to be filled with some data by myScript.js file.

JavaScript file
myScript.js

1
2
3
4
$(document).ready(function(){
 $("p").hide("slow");
 alert("Stop!");
});

Here the paragraph hide is called and before it finishes hiding, alert is called and every other operation of the webpage is halt until the user responds to the alert window. But if we want the paragraph to be hidden first and only after the paragraph is completely hidden we need to call the alert, in such case use callback methods as shown below:

JavaScript file: callback method
myScript.js

1
2
3
4
5
$(document).ready(function(){
 $("p").hide("slow", function(){
        alert("Stop!");
 });
});

If you want multiple things to occur after hiding the text(in above case) , you can nest the callback methods.

Anatomy of callback methods
JavaScript file: callback method
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function(){
eat("pizza", "cola", function(){
$("div").html("I had my food!");
});
 
});
 
function eat(food, drink, callback)
{
$("p").html("I ate "+food+" and had a "+drink);
 
if(callback && typeof(callback) === "function" )
{
callback();
}
 
}

Here we have a method called eat, which takes 3 parameters. First two are variable type and the 3rd parameter is a function type argument.

Once the page loads, we call eat method and pass pizza, cola and a callback method to it. After the first 2 variable values are displayed, eat method checks if the 3rd parameter is actually present and is a function – if so, it’ll call the function. So, the callback method is called after its preceding arguments are processed.

Anatomy and Working of Callback methods / anonymous functions


[youtube https://www.youtube.com/watch?v=lIPOER59ZSY]

YouTube Link: https://www.youtube.com/watch?v=lIPOER59ZSY [Watch the Video In Full Screen.]



Examples:
1. If we have calls to Facebook API, Twitter API and Google Finance API’s: Using JavaScript(jQuery or nodejs) we could send the request to all these API’s concurrently and not worry much about its response time. Once any of these API’s respond, the corresponding callback methods are called. So while these scripts are executed, it binds the callback methods to its calls, and then stops worrying about its response!

2. Many ad networks have implemented asynchronous ad codes, since these codes use callback methods and there is no need for the webpage to wait until the ad server responds. If and when the ad server responds with an ad, the page or the ad spot is filled with the ad.

Auto-Refresh DIV using jQuery

Video tutorial illustrates auto-loading / refreshing of particular div content, using jQuery.

For the purpose of illustration, we’re also adding fadeOut and fadeIn effects to it.
You can safely remove those effects!

With fadeOut and fadeIn effects

1
$('#auto').fadeOut('slow').load('load.php').fadeIn('slow');

Without fadeOut and fadeIn effects

1
$('#auto').load('load.php');

HTML Page with DIVs

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>Auto-Refresh DIV</title>
</head>
<body>
<div id="one">One</div>
<div id="auto"></div>
<div id="three">Three</div>
 
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="my_script.js"></script>
</body>
</html>

This HTML document contains 3 div’s.
First and third div’s has some content which remains constant since the page has been loaded.
DIV with an id auto, is refreshed for every 2000 millisecond and the content is being loaded from load.php file.

load.php

1
Apple Inc

jQuery Code
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
$(document).ready( function(){
$('#auto').load('load.php');
refresh();
});
 
function refresh()
{
setTimeout( function() {
  $('#auto').fadeOut('slow').load('load.php').fadeIn('slow');
  refresh();
}, 2000);
}

we have added fadeOut and fadeIn effects for the purpose of demonstration, you can remove it if you want.
2000 is the time for Timeout call, in milliseconds.

Auto-Refresh Specific HTML Section: using jQuery


[youtube https://www.youtube.com/watch?v=Ga3pOn7wXBA]

YouTube Link: https://www.youtube.com/watch?v=Ga3pOn7wXBA [Watch the Video In Full Screen.]



Output
Apple Inc

This will be useful for reloading a form or fetching fresh data from database.

jQuery Tutorial List

Follow the order in this post and make sure to practice all the tutorials and also share your knowledge with our awesome community on our official forum.

If you got to learn anything from our website, then please do not forget to share this page with your friends on Facebook, Google Plus, LinkedIn, Twitter etc..

1. jQuery Basics: Replace Text/String Inside HTML Document

2. jQuery: Selectors, Methods, Effects

3. callback methods / anonymous functions: jQuery

4. jQuery: Basic Image Effects

5. Animation of Text and Image: jQuery

6. Optimize / Improve Performance of jQuery Applications

7. Descendant Selectors: jQuery

8. Append/Add and Remove HTML/XML Elements: jQuery

9. Variables and Javascript Methods In jQuery

10. Animate Image with ‘this’ Selector: jQuery

11. jQuery Event Handling: Binding and Unbinding

12. Working With Images: Small jQuery Application

13. jQuery Methods and CSS: Restaurant Application

14. DOM Tree Traversal: jQuery

15. jQuery Filter Methods To Narrow Selection

16. Dynamically Load Images: jQuery Looping

17. Conditional Logic For Decision Making: jQuery

18. Detach and Attach DOM Elements: jQuery Array

19. Custom Functions: jQuery

20. Reading XML File Using jQuery AJAX Method

21. Insert Data Into MySQL: jQuery + AJAX + PHP

22. Objects, Arrays: JSON Using jQuery

23. Fetch JSON Data Using jQuery AJAX Method: getJSON

24. Fetch JSON Array Elements Using jQuery AJAX Method: getJSON

25. Fetch/Extract Data From Database Without Refreshing Webpage: jQuery

26. Registration Form Using jQuery + PHP + AJAX (PART 1)

27. Registration Form Validation: PHP + jQuery + AJAX (PART 2)

28. Login Form: jQuery + PHP + AJAX

29. Dynamic Image Slider / Gallery: jQuery

30. Auto-Refresh DIV using jQuery

31. Dynamic Suggested List: jQuery .get() method

Registration Form Validation: PHP + jQuery + AJAX (PART 2)

In this video tutorial we illustrate both client side as well as server side validation.

Client side validation using jQuery.
Server side validation using PHP.

To Solve:
Empty values shouldn’t be registered.
Duplicate usernames must not be allowed.
Display appropriate message, in case of duplicate username.

Explanation about HTML file (index.html), Database connection file(db.php):
Registration Form Using jQuery + PHP + AJAX (PART 1)

jQuery File: Client Side Validation
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$("#submit").click( function() {
 
if( $("#username").val() == "" || $("#pass").val() == "" )
  $("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
  $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
clear();
 });
 
$("#myForm").submit( function() {
   return false;
});
});
 
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

If the username and the password fields are empty, we display appropriate message and skip the execution of $.post() method.
This ensures that, we do not request data from the server when there is no need for it.

If the user has entered both username and password, then we execute $.post() method and pass the user entered data to process.php file.

PHP File: Server Side Validation
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
< ?php
      include_once('db.php');
 
  $username = mysql_real_escape_string( $_POST["username"] );
  $password = mysql_real_escape_string( md5($_POST["pass"]) );
  $fname = mysql_real_escape_string( $_POST["fname"] );
  $lname = mysql_real_escape_string( $_POST["lname"] );
 
 
  if( empty($username) || empty($password) )
  {
  echo "Username and Password are mandatory - from PHP!";
exit();
  }
 
 
 $res = mysql_query("SELECT username FROM users WHERE username='$username'");
  $row = mysql_fetch_row($res);
 
  if( $row > 0 )
    echo "Username $username has already been taken";
  else
  {
     $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
    if( mysql_query($sql) )
     echo "Inserted Successfully";
   else
     echo "Insertion Failed";
}
?>

At the beginning we check if the username or the password is empty. If they are empty, we echo Username and Password are madatory – from PHP and then stop further execution of the script.

If the username and password are not empty, then we check the user entered username against the usernames present inside the database. If the username is already present inside the database, then we intimate it to the user with a customized message.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)


[youtube https://www.youtube.com/watch?v=dRk1r4SfSyA]

YouTube Link: https://www.youtube.com/watch?v=dRk1r4SfSyA [Watch the Video In Full Screen.]



Why Validate both client side as well as server side ?
What if javascript has been disabled on client machine i.e., the browser ?
In this situation, our client side validation completely fails. So, server side validation is also important.

Then Why client side validation when server side validation could serve our purpose ?
This is because, client side validation is faster. i.e., if user tries to register empty data, it needs to travel across, reach the server, execute the validation rules script and then travel back to report that the user had submitted empty data and is not acceptable!
Instead of this lengthy, time consuming and costly process, we could simply write a client side validation and it responds back instantly, saving time, bandwidth and hence the cost of processing the data.