Search code examples
javascriptjqueryajaxpreventdefault

Unable to prevent form when a condition is met


I am working on a form I wish to validate via jQuery $.ajax. The form should only be submitted if a certain condition, data == 1

var preventSubmit = function() {
  return false;
  var form = $(this),
    name = form.find('#name').val(),
    email = form.find('#email').val(),
    comment = form.find('#comment').val();

  $.ajax({
    type: "POST",
    url: absolute_store_link + '/ajax/comments-filter',
    data: {
      name: name,
      email: email,
      comment: comment
    },
    success: function(data) {
      // if data is equal to 1,
      // submit form
      if (data == 1) {
        return true;
      }
    }
  });

};

$("#comment_form").on('submit', preventSubmit);

The submit happens regardless if the condition is met or not.

Where is my mistake?

If I use e.preventDefault();, how can I "undo" it in case if data is equal to 1?


Solution

  • You won't be able to allow the submission of the form with a return value of true because the ajax is happening asynchronously (by the time it completes the function has already finished executing). What you can do is always prevent the form from submitting in the preventSubmit function, then submit it programmatically.

    var preventSubmit = function() {
      
      var form = $(this),
        name = form.find('#name').val(),
        email = form.find('#email').val(),
        comment = form.find('#comment').val();
    
      $.ajax({
        type: "POST",
        url: absolute_store_link + '/ajax/comments-filter',
        data: {
          name: name,
          email: email,
          comment: comment
        },
        success: function(data) {
          // if data is equal to 1,
          // submit form
          if (data == 1) {
            form.off();//remove bound events (this function)
            form.submit();//manually submit the form
          }
        }
      });
      return false;//the return needs to be at the end of the function and will always prevent submission
    };
    
    $("#comment_form").on('submit', preventSubmit);