Mouad Nejjari Mouad Nejjari - 3 months ago 25
jQuery Question

How to call javascript validate function before form submit on an ajax call

Here is my validate() function, returns either true or false.
My problen is i want to call ajax submit form code only if validate() returns true, otherwise it will show the alert with error messages for not valid data and stay in page Without submitting the form , without using ajax I know that i can use if true return document.form2.submit();but in my case it doesn't work, Please help!

Ajax Code :

$("#form2").submit(function(){

var formData = new FormData($(this)[0]);
$.ajax({
url: "addv.php",
type: 'POST',
data: formData,
success: function (data) {
$('.fv').html(data).hide().fadeIn(500).delay(1000).fadeOut(500);
},
contentType: false,
processData: false
});

return false;
});


javascript function :

function validate()
{
var m=document.getElementById("mat").value;
var c=document.getElementById("kilo").value;
var v=true;
if(!isNaN(m))
{
alert("matricule doit etre une chaine !");
document.getElementById("mat").value=null;
v=false;
}
if(isNaN(c))
{
alert("kilométrage doit etre un entier !");
document.getElementById("kilo").value=null;
v=false;
}
return v;
}


Form :

<form enctype="multipart/form-data" class="form2" id="form2">
<label >Matricule</label></br>
<input type="text" name="mat"></br>
<label>kilométrage</label></br>
<input type="text" name="kilo"></br>
<label>Marque</label> </br>
<select name="mar" id="mar">
<?php
while($res=mysqli_fetch_array($req1))
{
echo "<option> $res[0] </option>";
}
?>
</select>
<label>Propriétaire Cin</label> </br>
<select name="pro" id="prop" onchange=fn()>
<?php
while($res=mysqli_fetch_array($req2))
{
echo "<option> $res[0] </option>";
}
?>
</select>
<label>Nom et Prénom</label> </br>
<input type="text" disabled id="propr"></br>
<label>Photo</label> </br></br>
<input type="file" name="img" id="img"style="color:red;"></br></br>
<input type="submit" value="Ajouter">
<b><p class="fv" style="color:red" align="center"></p></b>
</form>

Answer

You can use preventDefault to prevent submit of form. And use condition if validate returns true then use Ajax other case show alert

$("#form2").submit(function(e){
  e.preventDefault();
  if(validate()){

    var formData = new FormData($(this)[0]);
    $.ajax({
      url: "addv.php",
      type: 'POST',
      data: formData,
      success: function (data) {
        $('.fv').html(data).hide().fadeIn(500).delay(1000).fadeOut(500);
      },
      contentType: false,
      processData: false
    });     
  } else {
   alert('error');
  }
});