Book Image

PHP Ajax Cookbook

Book Image

PHP Ajax Cookbook

Overview of this book

Table of Contents (16 chapters)
PHP Ajax Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Sequencing Ajax Requests


As the name suggests, Ajax is asynchronous, so the sequence of code might not be followed, as most of the logical activities are done when the HTTP request is completed.

How to do it ...

Let's try to understand the Ajax request with an example:

$(document).ready(function()
{  
    $.ajax({
    type: "POST",
    url: "test.php",
    data:'json',
    data: "bar=foo",
    success: function(msg){
    console.log('first log');
    }
  });
   
  console.log('second log')
   
});

Once executed, the preceding code is seen as follows in the Firebug console:

How it works...

Although the $.ajax function is called first, due to the asynchronous nature of the code, the second log is printed first (as this line of code follows directly after the $.ajax function). Then, success: function gets executed when the HTTP request is completed and, after that, first log gets printed to console.

Sequencing Ajax requests is a technique that is widely used in real-time applications. In the following...