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.

Dynamic Suggested List: HTML5 + jQuery + PHP + MySQL

Today lets build a dynamic suggested list input field using HTML5, jQuery, PHP and MySQL.

Dynamic-suggested-list-html5-jquery-php-mysql

We have 55 company names in our database table – and the import file(.sql) can be downloaded at the end of this tutorial page. By using jQuery we pass user input to suggest.php file and the result is embedded into index.html file.

Related read: Suggested Entries Using datalist Element: HTML5

HTML file
index.html

<!DOCTYPE HTML>
<html>
<head>
<title>Dynamic Auto-Suggestion using datalist element: HTML5</title>
<meta charset="utf-8"/>
<script src="jQuery.js"></script>
<script src="myScript.js"></script>
</head>
<body>
 
<form>
<input type="text" list="myCompanies" name="company" id="suggest" />
<datalist id="myCompanies">
 
</datalist>
</form>
 
</body>
</html>

Here we have included jQuery library file before our script myScript.js
We also have an input field of type text, with an id = suggest, name = company and list = myCompanies. And a datalist element is linked/associated with input field, by matching it’s id with the name of input field’s list attribute. The value for option tag will be filled by jQuery, using the results output by suggest.php file.

PHP file
suggest.php

< ?php

    $db         = mysqli_connect('localhost', 'root', '', 'search');
    
    $company    = $_GET['company'];
    
    $sql        = "SELECT name FROM table1 WHERE name like '$company%' ORDER BY name";
    
    $res        = $db->query($sql);
    
    if(!$res)
        echo mysqli_error($db);
    else
        while( $row = $res->fetch_object() )
            echo "<option value="".$row->name."">";
        
?>

Here we connect php file to database(search). Get the keyword entered by the user in the input field and form a sql query. By using query() method, we process it and finally format it the way we need it i.e., we wrap the company names inside option tag’s value attribute.

jQuery file
myScript.js

$(document).ready(function(){
    $("#suggest").keyup(function(){
        $.get("suggest.php", {company: $(this).val()}, function(data){
            $("datalist").empty();
            $("datalist").html(data);
        });
    });
});

For every keyup event on the input field we trigger jQuery method $.get() and pass the user input keys to suggest.php file and the result is collected back by the callback function and the result set is stored in a variable called data.

Now we first make sure to clear out previous data present inside datalist element i.e., we clear the previous results by removing any option tags present inside datalist element. Now we fill the datalist element with the new data/result output from suggest.php file.

Since we’re using jQuery here, page does not reload and the suggested entries looks real and spontaneous.

Here is the list of company names I’ve taken for this tutorial

3M
7-Eleven
Accenture
Acer
Adidas
Adobe systems
Amazon.com
AMD
AOL
Apache
Apple inc
Appolo group
Aricent
Ask.com
Asus
AT&T
Bank of America
BBC
BE Aerospace
BMC Software
Boeing
Bosch Brewing Company
Boston Acoustic
CA Technologies
Citrix Systems
Cognizant Technolog
Cognizant Technology Solutions
Convergys
Dell
Delphi
DHL
Divx Inc
eBay
EMC Corporation
Exelon
Facebook
Ford Motor Company
Fox Entertainment Group
GCI
GoDaddy
Goodrich Corporation
Google
Hawaiian Airlines
Hewlett-Packard
Honeywell
IBM
Intel
Johnson & Johnson
KFC
McDonalds
Microsoft
Motorola
Nvidia
Red Hat
Yahoo!

Video Tutorials: Dynamic Suggested List: HTML5 + jQuery + PHP + MySQL


[youtube https://www.youtube.com/watch?v=YqMtE8UO-xw]

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


Note: For any older browsers which do not support datalist element or list attribute, it will simply fall back to text type input field and it doesn’t produce any error.

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