(JQuery) How to call a user-defined function before the next link

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

When clicking the link, I want:

  • First send (POST) some data back to the server
  • Second, let the browser go to the URL that the link points to.

I'm relatively new to jQuery, and here is my first attempt below. I will be grateful to any jQuery guru here to fill in the gaps (and possibly indicate how the snippet could be improved below).

<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>
+5
source share
5 answers

, . , ajax . , , , . , , , , . , :

$('#hotlink').click( function () { 
    $.ajax({ 
      async: false,
      type: "POST", 
      url: "http://myurl.com/mypage.php", 
      data: "param1=value&param2=value",  // &param3=value... etc. 
    }); 
}); 

.

+6

window.location ajax.

, :

<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>

, , , -, , ajax, , spinner , .

- -

- ajax, , .

, false, , ajax.

+4

:

$('#hotlink').click(function() {
    $.post(...);
    return true;
});

true .click(function(){...}) . return false, .

, , #hotlink hotlink ( ).

, $.post(...) jquery. : http://api.jquery.com/jQuery.post/

+1

ajax. (, post) - ajax.

$(document).ready(function(){
  $('#hotlink').click(function(){
     //AJAX Post data here ...
     $.ajax({
         async: false,
         data: 'can be a string or object, read docs',
         url: 'http://example.com/whatever.html',
         type: 'post'
     });

     //follow the link url (i.e. navigate/browse to the link) ...
     //(it happens naturally by clicking a link, no need for extra code)
  });
});

, , . , , , .

+1

;)

<script type="text/javascript">
$(document).ready(function(){
  $('#hotlink').click(function(event){
     //AJAX Post data here
  });
});
</script>

# . , event.preventDefault().

If you do not want to send an AJAX request, I suggest you send synchronous, otherwise you will not be able to determine whether it was successful or not.

0
source

All Articles