0

jQuery - How to remove click event preventDefault(), the code is like shown below,

$('button').on('click', 'loader', function(event){
    $.ajax({
          url: 'www.myweb.com/string/index.html',
          type: 'get',
          dataType: 'html',
           success: function(data){ 
             event.preventDefault(); 
             // something else 
           },
            error: function(data){
             // how to remove event.preventDefault(); here?
           }
});
olo
  • 5,225
  • 15
  • 52
  • 92
  • 2
    you can't do it like that because of the async nature of ajax – Arun P Johny May 25 '14 at 02:40
  • @ArunPJohny Thanks for the answer, was googling but didn't find a good answer. then I will try to find another way to archive my goal. – olo May 25 '14 at 02:41
  • With the nature of your [recent](http://stackoverflow.com/questions/23851575/passible-to-pass-ajax-inside-variable-value-to-global) questions I would highly recommend reviewing [Ajax Docs](http://api.jquery.com/jquery.ajax/). Most of your recent questions are covered there and it is invaluable when dealing with Ajax – MattSizzle May 25 '14 at 03:03

1 Answers1

2

As pointed out in the comments, the $.ajax function is asynchronous by default. Therefore, the success event handler would run after the click event handler has already returned.

If you really want to do this, you can specify the ajax call as synchronous, by setting the async option to false.

$('button').on('click', 'loader', function (event) {
    $.ajax({
        url: 'www.myweb.com/string/index.html',
        type: 'get',
        dataType: 'html',
        async: false
    }).done(function () {
        event.preventDefault();
    }).fail(function () {
        // Do something else here
    }));

Apparently you can't actually rollback preventDefault. Once you call it, you cannot uncall it. So it's important to only call the method in the success handler (or, in my modified example, the done method).

Community
  • 1
  • 1
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205