Thursday, May 3, 2007

Safari Ajax Problem

Ajax (or AJAX) is shorthand for "Asynchronous JavaScript and XML". It's clear that this technology imply asynchronous communication, but XmlHttpRequest object can do synchronized calls to server. Avoid this practice because it's not working in Safari browser.

We have used phpRequest class for such calls (http://www.phphacks.com/content/view/52/33/). It has execute() method which sends request to server, wait for response, and return it as result. Example of the code:

var httpReq = new phpRequest('myScript.php');
var resp = httpReq.execute();
// do something with resp...
alert(resp);

This approach is not works in Safari browser (not sure about version number). Small refactoring of this code and new method executeWithCallback() makes everyone happy :-)

var httpReq = new phpRequest('myScript.php');
var cb = function(resp) {
// do something with resp...
alert(resp);
};
httpReq.executeWithCallback(cb);

Code for executeWithCallback() is trivial I suppose. So, make your code really asynchronous to make it robust and avoid problems like this. Good example is SAJAX library: http://www.modernmethod.com/sajax

0 comments: