Tuesday, February 26, 2008

Asyncrhonous Ajax request modifing the session

Do not call 2 controller methods modifying session with Ajax asynchronously.

I searched hours for this bug in my code....

if the Task controller methods "select_project" and "select_project_resp" modify the session, then this code will ends up in a race condition. The resulting session will contain only the last modification.

function select_project(str){
if (str == "") return;
Element.show('loading');
new Ajax.Request('/task/select_project/' + str, {
asynchronous: true,
evalScripts: true,
onComplete: function(request){
display_tasks(request.responseText)
}
});
new Ajax.Request('/task/show_project_resp/' + str, {
asynchronous: true,
evalScripts: true,
onComplete: function(request){
display_project_resp(request.responseText)
}
});
return false;
}


Instead, call the second method after the first one finished:

function select_project(str){
if (str == "") return;
Element.show('loading');
new Ajax.Request('/task/select_project/' + str, {
asynchronous: true,
evalScripts: true,
onComplete: function(request){
display_tasks(request.responseText)
// to avoid race condition and mix the sessions,
// the second Ajax request is not done asynchronously
// but following the first....
new Ajax.Request('/task/show_project_resp/' + str, {
asynchronous: true,
evalScripts: true,
onComplete: function(request){
display_project_resp(request.responseText)
}
});
}
});
return false;
}


See http://www.chipmunkninja.com/article/asyncsessions

No comments: