jquery ajax GET request executing twice

gmh04 picture gmh04 · Mar 19, 2013 · Viewed 8.4k times · Source

I have the following ajax request that is executed at a click of a button:

<a href="javascript:test()"><img src="css/images/test.png"></a>

function test(){
    console.debug("*");

    $.ajax({
        type: "GET",
        dataType: "json",
        url: '/path/to/url',
        success: function(data){
            console.debug("**");
        }, 
        error: function(jqXHR, status, error){
            console.debug("*** " + status + " : " + error + " : " + jqXHR.status);
        },
        cache: false
    });
}

The request response takes approximately 30 seconds to return. However, the request is received and executed by the server twice as can be seen by the apache logs. The timestamp of the requests are 30 seconds apart but the request is identical (e.g ?_=1363692320782). The click response function is called once and the error callback is invoked once (exactly 60 seconds after initial request), although the apache response is a 200.

This problem has been reproduced in a Samsung Galaxy S2, android version 2.3.5 in a phonegap application.

UPDATE - adding Apache log entries from comment below

1.2.3.4 - - [19/Mar/2013:14:07:59 +0000] "GET /pcapi/records/dropbox/08342hjg9gpqm7g/?_=1363702072225 HTTP/1.1" 200 11139 "-" "Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"
1.2.3.4 - - [19/Mar/2013:14:08:29 +0000] "GET /pcapi/records/dropbox/08342hjg9gpqm7g/?_=1363702072225 HTTP/1.1" 200 11139 "-" "Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; GT-I9100 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"

UPDATE - adb logcat

I/Web Console(16747): * at file:///android_asset/www/js/mobile.js:1769
I/Web Console(16747): *** error : : 0 at file:///android_asset/www/js/mobile.js:1779

UPDATE - TCP/IP monitor

Putting the requests through a TCP/IP monitor shows both requests being sent with a 200 response for both.

Answer

Miguel-F picture Miguel-F · Mar 19, 2013

If your URL path defined here url: '/path/to/url' is to a folder and not a specific file try adding a trailing slash like this url: '/path/to/url/'.

What happens when a file is not specified is that the Apache web server sends a 301 redirect to the AJAX client with a new URL (with the trailing slash), so the client issues a new request to the proper URL.

See a similar question posted here: jQuery $.ajax() executed twice?

See the Apache doc reference here: http://httpd.apache.org/docs/2.0/mod/mod_dir.html#directoryslash