Single jQuery Ajax Call Results In Two Requests

I implemented simple performance monitoring for a JavaScript/Java application I’m building. This involved writing a Servlet Filter that calls Java Simon code. The Java Simon console application was recording two entries for every single Ajax request that was being made. It turned out the jQuery library was making two calls.

Double Ajax Request

Double Ajax Request

If you find that for every Ajax request made through the jQuery library you’re seeing two requests, it may be because you’re using CORS (Cross-Origin Resource Sharing). This is where your JavaScript makes an Ajax request to a server it was not loaded from.

In order to make a CORS call, jQuery makes a ‘preflight’ request:

Depending on the complexity of the cross-origin request, the client (browser) may make an initial request – known as a “preflight” request – to the server to gather authorization information. This preflight request can be cached by the client and is therefore not needed for subsequent CORS requests. – Ben Nadel

This results in two calls being made to the same URL. As I was recording data for performance monitoring I didn’t want the preflight requests to be included. There is no way to use the web.xml filter URL pattern to restrict by the HTTP method, so this had to be done in the Servlet Filter itself. (below) The preflight request uses the OPTIONS method, so I simply filtered on method.

//Absolutely not production quality code...
Split split = null;
try {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
 
        if (httpRequest.getMethod().equalsIgnoreCase("POST")) {
            String path = httpRequest.getPathInfo().replaceAll("/", ".");
 
            Stopwatch stopwatch = SimonManager.getStopwatch("servlet" + path);
            split = stopwatch.start();
        }
    }
 
    chain.doFilter(request, response);
} finally {
    if (split != null) {
        split.stop();
    }
}

 

This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *