I want to achieve the following behavior in a page link.
When the link is clicked, I want to:
I am relatively new to JQuery, and here is my first attempt below. I will be grateful to any jQuery gurus in here to fillin the blanks (and maybe point out how the snippet below may be improved).
<html>
<head>test page</head>
<body>
<div><a id="hotlink" href="http://www.example.com">Clik and see</a></div>
<script type="text/javascript">
$(document).ready(function(){
$('hotlink').click(function(){
//AJAX Post data here ...
//follow the link url (i.e. navigate/browse to the link) ...
});
});
</script>
</body>
</html>
You might want to see my answer to a similar question. Basically, an ajax post would be asynchronous by default and may not make it to the server before completing. In order to ensure completion, you can make it synchronous but this will lock up the browser until the request has returned. This can be very problematic if your server is having trouble, it could take a while and the user is waiting to follow the link. Nevertheless, the code is:
$('#hotlink').click( function () {
$.ajax({
async: false,
type: "POST",
url: "http://myurl.com/mypage.php",
data: "param1=value¶m2=value", // ¶m3=value... etc.
});
});
Upon completion, the default action of the link will be honoured.
You can set the window.location call in the ajax callback.
Here is some quick, untested code:
<script type="text/javascript>
$(document).ready(function(){
$('hotlink').click(function(){
var link = $(this);
$.post(url, {'data': 'value'}, function() {
window.location = link.attr('href');
});
return false;
});
});
</script>
Note that you should probably do something to make it clear that the page is doing an ajax call, like putting in a spinner graphic, and disabling the link so that they don't click it a bunch of times.
--edit--
The other way to solve this problem is to do a synchronous ajax call, but then the browser will lock up while it is in progress.
To answer the comment, you need to return false so that the link isn't followed until after the ajax call is successfully completed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With