Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Capture anchor href onclick and submit asynchronously

I almost never get to play with client-side stuff, and this presumably simple task is kicking my butt :)

I have some links. OnClick I want to prevent the default action, capture its href url, submit an ajax GET to that url, and simply alert() with the results ... but I can't even get past the starting line :)

Example anchors for play-time:

<a class="asynch_link" href="good/1.html">Click Here</a>
<a class="asynch_link" href="good/2.html">Click Here</a>

Now, I've played with a few suggestions for similar requests on SO, but the links still cause the browser to navigate to the href url.

Even with just

<script type="text/javascript">
    $('a').click(function (event) 
    { 
         event.preventDefault(); 
         //here you can also do all sort of things 
    });
</script>

...the links still navigate to the other page.

I'm kinda feeling like and infant here :)

Any and all help will be deeply appreciated.

And, yes, I AM including jQuery :)
<script src="//67.20.99.206/javascripts/jqueryCountdown/1-5-11/jquery.countdown.js" type="text/javascript" charset="utf-8"></script>

like image 408
mOrloff Avatar asked Sep 29 '12 00:09

mOrloff


3 Answers

$('a').click(function(event) { 
    event.preventDefault(); 
    $.ajax({
        url: $(this).attr('href'),
        success: function(response) {
            alert(response);
        }
    });
    return false; // for good measure
});
like image 181
mOrloff Avatar answered Oct 22 '22 12:10

mOrloff


Try this

$('a').click(function (event) 
{ 
   event.preventDefault(); 

   var url = $(this).attr('href');
   $.get(url, function(data) {
     alert(data);
    });

 });
like image 25
codingbiz Avatar answered Oct 22 '22 11:10

codingbiz


The problem here is that the Events are not being attached to your element because they are not being bound in DOM ready event . Try including your events in DOM ready event and if it works you will see the alert

<script> 
    $(function() {
         $('a').click(function(event) {
            event.preventDefault();
            alert('fff')
        //here you can also do all sort of things 
        });
    }); 
</script>

After this send the Ajax request and submit the form in the Success callback function..

<script> 
    $(function() {
         $('a').click(function(event) {
             event.preventDefault();
             $.ajax({
                 url: 'url',
                 dataType :'json',
                 data : '{}',
                 success :  function(data){
                     // Your Code here

                     $('#form').submit();
                 }
             })
        });
    }); 
</script>
like image 41
Sushanth -- Avatar answered Oct 22 '22 10:10

Sushanth --