Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I intercept a link with jQuery when using a ajax call?

Tags:

jquery

ajax

I might be doing 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 attach a jQuery click event to the link like so:

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

Everything works peachy. The page does not get redirected to /Not/Intercepted, which is what I would think would be correct.

Now...

I introduct a ajax call like $.get to my click event and now my page will be incorrectly redirected to the page, which essentially overwrites 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 click so it does not go to the href page? I want to keep the href for those users that aren't enabling javascript. TIA!

like image 421
rball Avatar asked Apr 25 '09 07:04

rball


People also ask

Can jQuery and AJAX be used together?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

How do I intercept all AJAX requests?

send = function(data) { var self = this; var oldOnReadyStateChange; var url = this. _url; function onReadyStateChange() { if(self. readyState == 4 /* complete */) { /* This is where you can put code that you want to execute post-complete*/ /* URL is kept in this.

Does AJAX follow redirect?

ajax appears to always follow redirects. How can I prevent this, and see the redirect without following it? There are various questions with titles like "jquery ajax redirect" but they all appear to involve accomplishing some other goal, rather than just directly checking the status that a server gives.


1 Answers

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've had many issues with IE especially not listening to return false. Apparently so have others http://coffeeandpaste.blogspot.com/2009/02/javascript-onclick-return-false-does.html

like image 116
Chad Grant Avatar answered Sep 27 '22 17:09

Chad Grant