views:

51

answers:

4

Hello

As I understand it and have used it, AJAX is used to make requests from the client to the server and to then update a HTML DIV on the client with new content.

However, I want to use AJAX from a client to a servlet to verify the existence of a URL. If the result is bad, I can set an error message in the servlet and return it to the client page for display.

But does anyone know if, in the case of a positive result, I can have my servlet automatically display another (the next) page to the user? Or should that request be triggered by Javascript on the client when the positive results is received.

Thanks

Mr Morgan.

A: 

In your success call back (on client), set the self.location.href to new URL.

Teja Kantamneni
Thanks. It works very well. I tried this through the servlet and it displayed the called page on the calling page. But self.location.href worked fine.
Mr Morgan
A: 

HTML is a "pull" technology: Nothing gets displayed in the browser that the browser hasn't previously requested from the server.

Hence, you don't have a chance to "make the servlet automatically display a different page." You have to talk your browser (from JavaScript) into requesting a different page.

Carl Smotricz
+1  A: 

Since your ajax call is executed in the background the result returned by the servlet, returns to the ajax call, which should then act accordingly to the result. e.g. trigger the display of another page. (Which could have been already in the ajax response and then you can show it in a div or iframe or ...)

Redlab
A: 

As per the W3 specification, XMLHttpRequest forces the webbrowser to the new location when the server returns a fullworthy 301/302 redirect and the Same Origin Policy of the new request is met. This however fails in certain browsers like certain Google Chrome versions.

To achieve best crossbrowser result, also when the redirected URL doesn't met the Same Origin Policy rules, you would like to change the location in JavaScript side instead. You can eventually let your servlet send the status and the desired new URL. E.g.

Map<String, Object> map = new HashMap<String, Object>();
map.put("redirect", true);
map.put("location", "http://stackoverflow.com");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
resposne.getWriter().write(new Gson().toJson(map));

(that Gson is by the way Google Gson which eases converting Java Objects to JSON)

and then in the Ajax success callback handler in JS:

if (response.redirect) {
    window.location = response.location;
}
BalusC
Have just tried the facility in Chrome, IE, Opera, Safari and Firefox and all seems well. but there's still a lot to do so I'll bear this in mind.
Mr Morgan
I wouldn't rely on it, you may be dependent on browser version as well. Just do the redirect in JS instead using `window.location`.
BalusC