Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(JQuery) How to call a custom function before following link

Tags:

jquery

I want to achieve the following behavior in a page link.

When the link is clicked, I want to:

  • First, send (POST) some data back to the server
  • Second, allow the browser to navigate to the url that the link was pointing 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>
like image 658
morpheous Avatar asked Apr 22 '10 22:04

morpheous


2 Answers

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&param2=value",  // &param3=value... etc. 
    }); 
}); 

Upon completion, the default action of the link will be honoured.

like image 159
Andy E Avatar answered Sep 30 '22 07:09

Andy E


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.

like image 23
zaius Avatar answered Sep 30 '22 07:09

zaius