Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing a function before redirecting from Anchor tag

I want to execute a jQuery function before redirecting after clicking on a tag, below is my code. The problem is that it only redirects and the jQuery post is not executed.

<script>
function insert(mobno) {
$.post("verification_back.php", {'mobno': mobno}, function(data) {
    if (data==1)
        alert('Inserted');
    else
        alert('Oops !!!');
    }); 
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">
<head>
    <title>Status</title>
</head>
<body>
<a onclick="insert(9999999999);window.location.href='https://api.whatsapp.com/';" href="#">9999999999</a><br/></body>
</html>
like image 672
www.friend0.in Avatar asked Nov 27 '25 03:11

www.friend0.in


1 Answers

The POST does not have enough time to finish before you have already executed the redirect. Moving it into your function fixes the issue. I added a 1 second timeout as well to delay the redirect if necessary.

function insert(mobno) {
$.post("verification_back.php", {'mobno': mobno}, function(data) {

    if (data==1)
        alert('Inserted');
    else
        alert('Oops !!!');
    }); 
    
    setTimeout(
      function(){
        window.location.href='https://api.whatsapp.com/';
      },
      1000
    )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">
<head>
    <title>Status</title>
</head>
<body>
<a onclick="insert(9999999999);" href="#">9999999999</a><br/></body>
</html>
like image 177
CodeMonkeyG Avatar answered Nov 29 '25 17:11

CodeMonkeyG