Tuesday, September 2, 2014

Keeping AJAX in sync

The front end of a web app needs to pick up data from a back end and do complex processing on it. An attempt would be to write AJAX on the front and process the returned data after the AJAX call. .

The JQuery code snippet below is triggered after an element with ID 'process' is clicked. An AJAX call sends a request variable, name of a city to a back end, which returns its population and stores to a variable. The variable is then alerted after the AJAX call.















The approach would seem perfect, except that the asynchronous part of AJAX lets the code continue the processing. While AJAX is still waiting for the response value, the application will continue to the next part of the code. The alert will show a null or undefined value.

So there is now a need to keep the execution of AJAX in sync with the remainder of the code. This can be achieved by using anonymous functions as parameter as shown below:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery-AJAX-JSON</title>
<style>
div#result{
 color:blue;
 width:
}
</style>
<script src="jquery-1.11.1.min.js"></script>
<script>


$(document).ready(function (){
 function get_population(show_population){
  var city = 'Manila';
  var city_population = '';
  //execute ajax to pass requestvalues and get response output
  $.ajax({  
   url: 'get_population.php',
   type: 'post',
   data: { City: city},
   dataType: 'json',
   success: function(json) {
    city_population = json.population;
    show_population(city, city_population);
   },
   error: function(xhr, ajaxOptions, thrownError) {
    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + "Err-01");
   }
   
  });
 } 
 
 function init_get_population(){  
  get_population(function(city, population){
   alert('Population of ' + city + ': ' + population);
   //continue processing the returned value
  });
 }

 $("#process").click(function(){
  init_get_population();  
 });
});

</script>
</head>

<body>

<form action="#" method="post">
<input id='process' type="button" name='submit' value='process' />
</form>
</body>

</html>

The anonymous function approach is similar to the click event handler. As soon as the element with ID 'process' is clicked, the function init_get_population() is called.













The init_get_population() will in turn call function get_population() but notice that the parameter being passed. Instead of typical value, an unnamed function is passed. This unnamed function is the anonymous function to keep our AJAX code is sync.







The anonymous function will in turn take in parameters of its own, variables city and population.

The function get_population() has the parameter- show_population,to "connect" to the anonymous function.


The function get_population initializes two variables, city and city_population. City will contain the value to be passed as request parameter to the AJAX call. City_population will contain the returned value.

The AJAX call will start with the settings show below. The back end URL called handles a Post HTTP request and return JSON formatted data.

The success setting below shows how the AJAX call will be in sync with the anonymous function. 

The variable city_population takes the returned population from the JSON response. The parameter show_population connects to the anonymous function will pass the city and an city_population values as parameters.
The call to the anonymous function lets us process the returned value as how we need it. Taking this approach, we are able to synchronize AJAX call with our code.

Got a question or have any web coding you'd like me to help you out? I'd be more than happy to assist you and blog about it!

Just drop me an email at jrundolor@gmamail.com and tell me more about it!

No comments:

Post a Comment