Search code examples
javascriptfunctiononclickhref

Link redirects page before javascript onclick function is able to finish


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;
}

Solution

  • 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;
    });