0

I am a java/jquery novice and struggling with the following:

$(document).ready(function() {
//Prevent SUBMIT if Session setting = On (Ajax)
$('#formID').submit(function(e) {
    var prevent = false;
    $.ajax({
        type: "POST",
        url: "url/to/ajax_file.php",
        cache: false,
        success: function(res){
            if(res == "On") { alert('Session is ON so submit should be prevented'); prevent = true; }
        }
    });
    if (stop2) { e.preventDefault(); }
});

});

The session setting is returned ok, and the alert is presented. But I also want to prevented the form submit if the session setting returned = 'On'. This is not happening. There is obviously something I do not understand, any advice?

labbetuss
  • 3
  • 3
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Feb 09 '16 at 06:51

1 Answers1

2

You can't do that because of the asynchronous nature of ajax requests, instead in the submit handler you need to directly prevent the default action then in the ajax handler you can submit the form programatically.

$(document).ready(function() {
  //Prevent SUBMIT if Session setting = On (Ajax)
  $('#formID').submit(function(e) {
    e.preventDefault();
    var form = this;
    $.ajax({
      type: "POST",
      url: "url/to/ajax_file.php",
      cache: false,
      success: function(res) {
        if (res == "On") {
          alert('Session is ON so submit should be prevented');
        } else {
          form.submit();
        }
      }
    });
  });
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531