Jump to content

prevent form from submitting if ajax call returns false


brianlange

Recommended Posts

I would like to run preventDefault() if the ajax call fails.

How do I set the sf variable inside of my ajax complete function?

 

$(document).ready(function() {
   
    
    $('#login').submit(function(e){
    
         var sf = true;
         
        $.ajax({type: 'POST', 
                url: '/index/check-email', 
                async: 'false', 
                data: {email: '[email protected]' }, 
                complete: function(XMLHttpRequest, textStatus) {
            
                if (XMLHttpRequest.responseText == 'fail') {
                    
                    $('#norisk').css("display", "none");
                    $('p.error').css("display", "block");
                    sf = false;    
                } else {
                    alert(XMLHttpRequest.responseText);
                }
       }});
       
       
       if (!sf) {
          e.preventDefault(); 
      }
    
  });
});

Thanks for the response. I want to call e.preventDefault() based upon the results of the ajax call.

e.preventDefault() only appears to work outside of the ajax call and I can't get the result of the ajax call outside of the scope of the ajax function.

so when you do this

sf = false;

 

Nothing happenes?

 

Also you might try the $.data() method.

Just attach $(whatever).data('failed')

And check if($(whatever).data('failed')){ do your shtuff}

 

This is more of a workaround than a direct solution to you method.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.