6

How to detect an ajax request in the best possible way?

I'm currently using this in my controller:

private boolean isAjax(HttpServletRequest request){
    String header = request.getHeader("x-requested-with");
    if(header != null && header.equals("XMLHttpRequest"))
        return true;
    else
        return false;
}

But I don't like this way, I think there should have a better solution with Spring.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
Fernando Nogueira
  • 1,302
  • 1
  • 14
  • 22
  • Can you add to your question as why you want to do it at high level, there are more chances of getting better solutions... – minion May 26 '15 at 14:55

2 Answers2

15

That is the only "generic" way to detect an Ajax request.

But keep in mind: that's not failproof, it is just a best effort attempt, it is possible to make an Ajax request without sending the X-Requested-With headers.

jQuery usually includes that header. Maybe another lib doesn't. The protocol certainly doesn't consider that header mandatory.


Just a note: Your code is perfectly valid, though you could write it a bit simpler:

private boolean isAjax(HttpServletRequest request) {
    String requestedWithHeader = request.getHeader("X-Requested-With");
    return "XMLHttpRequest".equals(requestedWithHeader);
}
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
0

There is a simple bullet proof solution. Simply send query parameter like ajax=1 from your ajax request and send a different value or do not send this parameter for regular request and check in your controller and take action accordingly.

ace
  • 11,526
  • 39
  • 113
  • 193