What is a race condition? A race condition is a flaw in a system or process whereby the output and/or result of the process is unexpectedly and critically dependent on the sequence or timing of other events. (Wikipedia on Race Conditions.).
So far, so good.
How does race conditions appear using Ajax?
It happens when two or more operations are started, and the result of these operations needs to be displayed AFTER all operations has been finished.
For example: You want to display the different types of information like price, weight, dimensions of a car. For each of these information, you use an Ajax operation (It is no question, that this problem can be also solved in other ways). Now…you want that these information are displayed AFTER all figures has been determined.
But where is the problem? Have a look at the following code:
function determineFigure() { var serialNo = "XK8LBV42". getPrice(serialNo); getLength(serialNo); getWidth(serialNo); getHeight(serialNo); displayFigures(); } function getPrice(serialNo) { ... Ajax Operation ... } function getLength(serialNo) { ... Ajax Operation ... } function getWidth(serialNo) { ... Ajax Operation ... } function getWeight(serialNo) { ... Ajax Operation ... } function displayFigures() { ... Display operation }
The problem is that the “displayFigures()” will be called before all the figures has been determined. How come? Each Ajax request has to be transmitted, processed
and the result has to be sent back to the client. This all takes time; and definitely more time to invoke the methods mentioned above!than invoking the four methods.
So how can we solve this problem? I would like to introduce here two options: “Chaining” and “Counting”
Option 1: Chaining
Each Ajax request has a so called “Callback Method”. See code below!
function getPrice(serialNo) { $.ajax( { type: "POST", // Set the Post Method url: "/keyFigureController.php, // Set the target url data: "serialNo=" + serialNo + "&type=price", // set the parameters success: function(msg) { getLength(serialNo); }, error: function(msg) { } }); }
These methods are called in case of an successful (“success”) or errorneous (“error”) outcome of the request. So, what you can do here, is to write in each success method the next method until every figure is determined and the information can be displayed.
Option 2: Counting
Another way is to count the number of completed requests.
function getPrice(serialNo) { incrementTotalRequestCounter(); $.ajax( { type: "POST", // Set the Post Method url: "/keyFigureController.php, // Set the target url data: "serialNo=" + serialNo + "&type=price", // set the parameters success: function(msg) { incrementProcessedRequestCounters(); addNumberToTable(); checkCounter(); }, error: function(msg) { } } ); } function checkCounter() { incrementProcessedCounter(); if(getTotalRequestCounter == getProcessedCounter()) { showDialog(); } }