title: Javascript - Stop form submit depending on ajax response
body: <p>I'm wanting to use AJAX to determine whether or not a form's values are acceptable to me (this is not form validation). The AJAX <code>result</code> will determine if the form is submitted or not.</p>
  
  <p>Below, you'll see that I perform an AJAX call when the form is submitted and depending what is returned (either blank which is acceptable, or an error message which is not acceptable), I'd like to <code>return true;</code> or <code>return false;</code> the <code>$("form").submit</code>.</p>
  
  <p>I suspect my trouble to be in the AJAX's <code>success:</code>. Please help me get the <code>result</code> out of the AJAX call so that I can do something like <code>if (result == "") { return true; } else { return false; }</code>.</p>
  
  <p>WORKING:</p>
  
  <pre><code>$("form").submit(function(e) {
      e.preventDefault();
      var form = this;
      var tray = $('select[name=tray_id]').val();
      $.ajax({
          type: "POST",
          url: "modules/reserve-check.php",
          data: {tray_id: tray},
          cache: false
      }).done(function(result) {
          if (result == "")
              form.submit();
          else
              alert(result);
      }).fail(function() {
          alert('ERROR');
      });
  });
  </code></pre>
  
  <p>ORIGINAL:</p>
  
  <pre><code>$("form").submit(function() {
      var tray = $('select[name=tray_id]').val();
      $.ajax({
          type: "POST",
          url: "modules/reserve-check.php",
          data: {tray_id: tray},
          cache: false,
          success: function(result) {
                  alert(result);
          },
          error: function(result) {
              alert(result); //This works as expected (blank if acceptable and error msg if not acceptable)
          }
      });
  
      /*
      if (result == "")
          return true; 
      else
          return false; 
      */
      return false; //this is here for debugging, just to stop the form submission
  });
  </code></pre>