views:

252

answers:

4

Hi,

I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned:

{"authentication":"required"}

The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page.

However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options:

  1. Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time!

  2. The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection.

If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on.

Cheers, Don

+3  A: 

3) Change your AJAX code to add a variable to the GET or POST: outputJson=1

Greg
+1  A: 

You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page.

There are two options that I can see: Add a parameter to the page by appending a URL parameter to the screen that modifies the output.

URL: http://domain/page.jsp?ajaxRequest=true would output json only

URL: http://domain/page.jsp would display a jsp page that could forward to another page.

OR

change the response to have the forwarding code in the JSP that will get executed by the web browser if it is hit directly. Then have your calling AJAX to strip the forwarding code out, and then process what is left.

Rontologist
A: 

4) Read up on the 'Accept' request HTTP header.

Then, on the server side tailor the output:

e.g.

if(Accept contains application/json...) { // client asking for json, likely  to be XHR
  return {"foo":"bar"}
} else { // other
  return "Location: /login-please";
}
AlexJReid
A: 

Start with a smarter error message, like this:

{"error":"authentication required"}

Wrap the JSON output in a callback:

errorHandler({"error":"authentication required"});

Have a handler waiting in your script:

function errorHandler(r) {
   alert(r.error);
}

And don't forget to send it down as text/javascript and not application/x-json.

Kent Brewster