...">

How to intercept link with jQuery when using ajax call?

I could do something stupid. But if I have a normal link like:

<div id="changeMe"></div> <a href="/Not/Intercepted" id="interceptMe">A link</a> 

and I am attaching a jQuery click event to a link like:

 $('#interceptMe').click(function() { $('#changeMe').text('Changed'); return false; }); 

Everything works peach. The page is not redirected to / Not / Intercepted, which I think will be correct.

Now...

I injected an ajax call, such as $ .get, into my click event, and now my page will be redirected incorrectly to the page, which essentially rewrites the ajax call.

 $('#interceptMe').click(function() { $.get('/Ajax/Call', goesIn, function(comesOut) { $('#changeMe').html(comesOut); }, "html"); return false; }); 

Is there a way to make jQuery or javascript still intercept the link so that it doesn't go to the href page? I want to keep href for those users who do not support javascript. TIA!

+10
jquery ajax
Apr 25 '09 at 7:38
source share
1 answer

instead of return false, use ....

 $("#interceptMe").click(function(event){ event.preventDefault(); // Ajax here return false; //for good measure }); 

http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29

I had a lot of problems with IE, especially not listening to return false. Apparently there are other http://coffeeandpaste.blogspot.com/2009/02/javascript-onclick-return-false-does.html

+22
Apr 25 '09 at 8:03
source share
— -



All Articles