0
<a id="ad_server_ad" name="1" href="http://google.com">
<img src="xyz.png"></a>

Above is my html code:

This is my js code :

$(document).ready(function(){

$('a#ad_server_ad').click(function() {
    var name = this.name;

$.post("ajax_test.php",{ test:name },function(data){
                alert(data);
        });


});});

And this is my ajax_test.php

if(isset($_REQUEST['test']))
{
    echo "Call made successfully" . $_REQUEST['test'];
}

The code works perfectly fine for the first ajax call but after that when I open the page again and click on the image once more the ajax call is cancelled as shown in networks/XHR. If I wait for a few mins it works again but just for once.

Now if I use the same code in Incognito mode it works for all the consecutive click. I am new to ajax and jquery so help me.

Ashish
  • 539
  • 6
  • 18

2 Answers2

0

As far as I know, It may involve browser caching. Try to add a random number for each request, i.e. "ajax_test.php?12345".

This should trick the browser to not cache the request. Check this answer: Prevent browser caching of jQuery AJAX call result

Community
  • 1
  • 1
balanza
  • 1,012
  • 1
  • 12
  • 32
  • 1
    `POST` requests aren't cached. – Musa Jan 04 '15 at 15:51
  • I too thought that its the issue of cache but the documentation says "Pages fetched with POST are never cached".. So I am clueless as in what to do.. – Ashish Jan 04 '15 at 15:52
0

EDIT: Sounds unrelevant answer, i cannot think how this could be related to described behaviour in question...

You should prevent defaut behaviour of anchor's click:

$(document).ready(function () {
    $('a#ad_server_ad').click(function (e) {
        e.preventDefault(); // prevent click anchor default behaviour
        var name = this.name;
        var self = this;
        $.post("ajax_test.php", {
            test: name
        }, function (data) {
            alert(data);
            // to redirect, you could use:
            window.location = self.href;
        });
    });
});
A. Wolff
  • 72,298
  • 9
  • 84
  • 139
  • Well your solution worked and ajax calls are being made now.. But I wanted the default behaviour to work as well.. – Ashish Jan 04 '15 at 16:11
  • And I still dont understand.. why is it working in incognito. – Ashish Jan 04 '15 at 16:12
  • I know this would work.. The thing is, this defeats my purpose of doing the task of redirecting the user and making ajax calls simultaneously.. I could have had redirected the user from the php file also.. – Ashish Jan 04 '15 at 16:18
  • You cannot make a redirect and ajax call simultaneously. In fact you can BUT you have no garanties the request will have enough time to complete and usually browser cancel it once a redirection is in process – A. Wolff Jan 04 '15 at 16:42