Wednesday, July 15, 2009

Asynchronousity vs. Synchronousity in AJAX

Sometimes it is necessary to halt script execution until an ajax request has successfully returned and handled data it processes.

By default, your script will be executed one line after the other (asynchronously) while running the ajax process in the background. This means that after you make your ajax call, the script moves right on to the next line while your ajax call executes in the background eventually calling its own success function when data is returned.

Let's say your script depends on processed data from an ajax call that happens prior to your use of another function or conditional test. In this case, you will most likely want to halt the further execution of your script until after the ajax call has completed. This will insure that you get the data you're expecting and not spending hours debugging and banging your head on a wall.

The fix is extremely simple in jQuery. Let's take a look...


function asyncAjaxCall(e){

var hasChanged = 0;

$.ajax({

type:"POST",

url:"myapp.php",

data:"d=" + e,

dataType:"text",

success:function(data){

if(data == "changed"){

hasChanged = 1;

}

}

)};



if(hasChanged){ doThis(); }

else{ doThat(); }

}


In the above example, asynchronicity is assumed and try as you may, only the doThat function will be called because immediately after executing your ajax statement, the function begins to execute your conditional statement. Because your ajax success statement hasn't finished its execution, the data returned will be processed after your script has finished execution and hasChanged has not been handled as you might have expected.

To prevent this, we need to disable the asynchronous behavior of the ajax call to make sure that the script doesn't do anything before we have had a chance to process the data returned. The function below will take care of that...


function syncAjaxCall(e){

var hasChanged = 0;

$.ajax({

async:false,

type:"POST",

url:"myapp.php",

data:"d=" + e,

dataType:"text",

success:function(data){

if(data == "changed"){

hasChanged = 1;

}

}

)};



if(hasChanged){ doThis(); }

else{ doThat(); }

}


By default, async is true when you make a call with a jQuery ajax statement. By setting async to false, we force the function to wait until after the ajax's success event has had a chance to do something with our data giving us a chance to use that information later in our conditional statement.

No comments:

Post a Comment