Juliatzin
Juliatzin

Reputation: 19695

Disable link action when Making AJAX Call

I have a link UNDO that call my controller Restore().

Thing is I can't disable link calling the controller.

So, it opens it with a Json response instead of staying in the same page.

Here is my code:

The link:

<div class='row'>
   <div class='col-lg-8'>" + data.msg + "</div>
   <div class='col-lg-4' align='right'>
      <a class='undo' href='"+ url+ '/' + dataId + "/restore' 'data-restore' =" + dataId +" >
        <span class='undo_link'>UNDO</span> </a>
  </div>
</div>

The AJAX Call that should cancel the Link:

$('.undo').click(function (e) {
    e.preventDefault();
    e.stopPropagation();

    // ... All my ajax stuff.
}

Any Idea why is doesn't respect: e.preventDefault()?

Upvotes: 1

Views: 1593

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

This issue is because you're calling preventDefault() on the span element, yet the link that's followed is on the parent a element. This means you either need to use stopPropagation(), to stop the link being fired on the a:

$('.undo_link').click(function(e) {
    e.stopPropagation();
    // All my ajax stuff.
});

Or alternatively hook to the click event of the a itself by putting the undo_link class on that element:

<a href="' + url + '/' + dataId + '/restore" data-restore="' + dataId + '" class="undo_link">
    UNDO
</a>

Also note that if the element is appended after the DOM has loaded you need to use a delegated event handler:

$(document).on('click', '.undo_link', function(e) {
    e.preventDefault();
    // All my ajax stuff.
});

Upvotes: 1

Related Questions