Monday, August 24, 2009

How To Redirect AJAX Request

There are so many questions out there asking about how to redirect AJAX / XmlHttpRequest. It is usually needed when you provide user login page with AJAX. We ask user for username and password then we send the data to server via AJAX. Server validates user's data. If they are valid we want to redirect user to another page. That's what we want.

Unfortunately, AJAX cannot do that. Why?

AJAX (Asynchronous Javascript And XML) is a kind of asynchronous communication between client and server. The meaning of asynchronous is that the communication is closed after client sending the data. But it's not ending. Client is still waiting for server response. Once the response come, it is retrieved by callback function in client.

We can make an analogy by sending SMS to your friend. SMS is also a kind of asynchronous communication (while Phone Call is synchronous). When you finish sending SMS to your friend, your mobile phone actually stop sending data to your friend. But the phone is still waiting for the reply from your friend. You cannot know when your friend will reply. It could be in a minute, an hour or there will be no reply.

That's an example of asynchronous communication. So what the point?

In web-based communication architecture, if the data is sent asynchronously to server then the response will not be displayed in browser page. It will be passed to callback function that was set just before sending data. That's why we cannot redirect user with AJAX request. The redirection will only occur in server-side not in client-side.

So if we want to redirect AJAX request, it must be done by javascript on client. The server can just send back status message wheter login is failed or succeded. If success, change the page location by javascript. You can do this by this command
window.location = 'http://www.example.com';

Don't forget to leave a comment so I know that this post is useful to you.

No comments: