Nicero Nicero - 7 months ago 13
Javascript Question

'Alajax' Jquery simple form submit. How to prevent submitting if form not validated?

I was looking for a simple JQuery plugin to make it easy to submit forms via Ajax and I found Alajax which I found handy as it integrates into a typical HTML form and does all the job. Unfortunately I don't understand how to prevent the form to be sumbitted if it is not validated (the official web site is quite poor of documentation, nor the author has answered my mail).

For example the following form is submitted via Ajax: the plugin intecepts the form, grabs the 'name' attributes and call send.php as a normal form

<form id="myform" action="send.php">
<input type="text" name="firstname"
<input type="submit" value="Submit">
</form>

<script>
$(document).ready(function (){
$("#myform").alajax();
});
</script>


Alajax has some options as explained:

$('#myform').alajax({
type: '' // Type of return value. Default is "text". Other values are: "json", "xml", "jsonp"
beforeSend: function (){} // Code to run before sending the form
success: function(){} // Code to run when the AJAX call success
error: function(){} // Code to run when error occures
});


But the following code still submits the form:

$('#myform').alajax({
beforeSend: function (){
// Validation code is here. Suppose that form is not validated,
return false; // this should'nt stop submitting the form?
}
});


The code inside the beforeSend option is correctly executed (as I tested it with a call to console.log), but the form is still submitted. How I can prevent the form to be submitted upon an error? I also tried preventDefault without success.

Answer

You can't prevent the form submition with alajax. however you can use another submit listener to prevent the event from reaching alajax.

<form id="myform" action="send.php">
  <input type="text" name="firstname">
  <input type="submit" value="Submit">
</form> 

<script>
  $(document).ready(function (){

    $("#myform").submit(function(e){
      e.preventDefault();
      if(/* form is invalid */){
        e.stopImmediatePropagation();
      }
    });

    $("#myform").alajax();
  });
</script>
Comments