The link redirects the page before the onclick javascript function can finish

I have a link that loads a page and calls the javascript function on click. The problem is that the javascript function cannot finish before the page is redirected. Is there any way to guarantee this?

You will notice there alert() , which is commented out in the javascript function, and if I uncomment it, the function will be able to complete. However, I obviously do not want the warning popup to actually take place.

Here's the link:

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

Here is a javascript function that cannot finish on time:

 function setYSession() { var YposValue = window.pageYOffset; $.get('yPosSession.php?yValue=' + YposValue); //alert(YposValue); return false; } 
+8
javascript function href onclick
May 23 '12 at 1:58
source share
2 answers

Try changing 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 behavior, i.e. generally stop link navigation. Then in your function, you can add code for navigation after the completion of Ajax:

 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 if you use jQuery for $.get() , I remove 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; }); 
+13
May 23 '12 at 2:04 a.m.
source share
 <script> function a() { setYSession(); window.location.href = "p.php?p=$randString&s=$postCat"; return false; } </script> ... <a href='javascript: void(0);' onclick='a();'>click me</a> 
-one
Sep 25 '14 at 14:52
source share



All Articles