Ajax Programming Common Errors

Friday, July 18, 2008

You might already know about it, but I think It's still worth mentioning, the common issue some developers stumble on:

1. GET Requests Caching on Browsers
Sometimes, when making repeated GET XMLHttpRequest to the same uRL can lead to the response coming from the browser cache and not from the server. Especially when you're using Internet Explorer. And this IS annoying.

With no-cache or similar HTTP headers, this problem can be solved, theoritically, but in a real life coding this cache is sure difficult to get rid off.

The most effective way to solve this problem is add an always update or random variable to the URL where the request is sent. So the browsers read this request as a different page request and returns the server page rather than the cached version.

So, if usually we send a request like this
var url="somescript.php?var1="+var1; XMLHttp.open("GET", url);
Now we just simply add a random varible like this
var url="somescript.php?var1="+var1+"&rand="+new Date().getTime(); XMLHttp.open("GET", url, true);


2. Escaping Variables
Remember, when creating GET or POST requests, you must escape every variables that have possibility to contain nontext characters or spaces. It's a good way to avoid crafted variables by people who like to mess or just test your codes. It goes simply like this:
XMLHttp.open("GET", url+escape(var1)+"?rand="+new Date().getTime(), true)

3. Permission Denied
Usually means that you have cross-domain scripting requests happen. Like what I've wrote earlier, an XMLHttpRequest object can't be made across different domains by default due to security matter. So by default, calls must be made to server scripts existing in the same domain as the calling scripts. And please notice that domain must be written EXACTLY in the same way, mydomain.com may be interpreted as different domain from www.mydomain.com, thus, permission will be denied. Here and here, you can find out how to solve this cross-domain issue.

0 comments: