Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to differentiate Ajax requests from normal Http requests?

I am using JSF framework in my application. I need to run a specific script before the render response phase in my Phase Listener class.

Condition for running this script is that, if the request triggered is a Ajax request i need to run the script, if the request triggered is a Http request i should not run that script.

Can anyone please help me to differentiate the requests recieved.?

like image 227
R K Avatar asked Feb 03 '11 12:02

R K


2 Answers

Ajax requests have usually a X-Requested-With: XMLHttpRequest request header. In JSF, you can obtain the request headers by ExternalContext#getRequestHeaderMap().

ExternalContext externalContext = facesContext.getExternalContext();
Map<String, String> headers = externalContext.getRequestHeaderMap();
boolean ajax = "XMLHttpRequest".equals(headers.get("X-Requested-With"));
like image 102
BalusC Avatar answered Nov 12 '22 09:11

BalusC


Ajax requests set a server variable X-Requested-With to XMLHttpRequest. You can use that information to differentiate between ajax and normal requests.

like image 35
Tatu Ulmanen Avatar answered Nov 12 '22 08:11

Tatu Ulmanen