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>
CodePudding user response:
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>
CodePudding user response:
This will ensure jQuery function execution before redirecting
function insert(mobno, link) {
$.post("verification_back.php", {'mobno': mobno}, function(data) {
if (data==1)
alert('Inserted');
else
alert('Oops !!!');
}).done(function() {
window.location.href=link;
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>