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?

1

1 Answer 1

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();
        }
      }
    });
  });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Prevents submit if res == 'On', but does not submit if res!== 'On'. Console says:"Uncaught TypeError: form.submit is not a function"
do you have a button named/id as submit in your form... if so rename the button
Indeed I had, several of them, just tested ok, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.