9

I have a link that loads a page and calls a javascript function on click. Problem is the javascript function can't finish before the page redirects. Is there anyway to ensure it does ?

You will notice there's an alert() that is commented out in the javascript function, and if I uncomment it, the function is able to complete. However, I obviously don't want an alert popup to actually take place.

Here is the link :

<a href="p.php?p=$randString&s=$postCat" onclick="setYSession();">

Here is the javascript function that can't finish in time :

function setYSession() {
    var YposValue = window.pageYOffset;
    $.get('yPosSession.php?yValue=' + YposValue);
    //alert(YposValue);
    return false;
}
user1399694
  • 103
  • 1
  • 1
  • 5

1 Answers1

13

Try changing the onclick to return the result of your function:

echo "<a href='p.php?p=$randString&s=$postCat' onclick='return setYSession();'>";

Or explicitly return false:

echo "<a href='p.php?p=$randString&s=$postCat' onclick='setYSession();return false'>";

Given that your function returns false, either way will stop the default event behaviour, i.e., it will stop the link navigating at all. Then within your function you can add code to do the navigation after your Ajax finishes:

function setYSession() {    
    var YposValue = window.pageYOffset;
    $.get('yPosSession.php?yValue=' + YposValue, function() {
       window.location.href = 'p.php?p=$randString&s=$postCat';
    });

    return false;    
}

Ideally, especially since you seem to be using jQuery for the $.get(), I'd remove the inline onclick and do something like this:

echo "<a href='p.php?p=$randString&s=$postCat' id='myLink'>";

$("#myLink").click(function() {
    var YposValue = window.pageYOffset,
        myHref = this.href;
    $.get('yPosSession.php?yValue=' + YposValue, function() {
       window.location.href = myHref;
    });

    return false;
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Went with your 2nd to last recommendation and it works like a charm! – user1399694 May 23 '12 at 02:57
  • 1
    After implementing behaviors like this, you may get stuck with the same problem I did: your control+click won't work. You're breaking standard browser behavior, and you'll regret that later on. – Spork Jan 28 '14 at 15:13