views:

409

answers:

2

How can I delay loading of an anchor link until after a $.get request has gone out? I have

$("a.track").click(function() {
    $.get("track.php", { id: "page1.html" });
});

... but clicking on the link loads the new page before the above request goes through (my response on the PHP page is not recorded). If I stop the link using return false;, the $.get request works as expected, but now the link doesn't load.

What I'd like is to do something like

$.get("track.php", { id: "page1.html" }, function() {
    return true;
});

... but the new page loads before this can be executed, so it doesn't work as expected.

How can I make the loading of this link only happen once the GET request has been sent? I don't really care about getting a result back from the request, I just want it sent before the new page loads.

A: 
$("a.track").click(function() {
    var that = this;
    $.get("track.php", { id: "page1.html" }, function(){
        $(that).attr('onclick', '').click();
    });
});

or something like that. You'll have to kill you're former click event handling attr('onclick', '') may or may not do it.

defrex
+6  A: 

You can pass the click handler a callback, which would redirect the page upon success.

$("a.track").click(function(event) {
  event.preventDefault(); // Ignore user's click
  var href = $(this).attr('href');
  $.get("track.php", { id: "page1.html" }, function(data){
    window.location = href; // Redirect on success
  });
});
Ron DeVera
yours is probably better, since you don't have to worry about calling the click handler again.
defrex
Perfect. Exactly what I was looking for. Thanks!
neezer