Mouad Nejjari
Mouad Nejjari

Reputation: 107

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>

Upvotes: 0

Views: 4839

Answers (4)

Vikram Singh Chandel
Vikram Singh Chandel

Reputation: 1308

Try This

$("#userFrm input,#userFrm  select").each(function(index, value){
                if(value.checkValidity()==false){
                alert("error message");
                return false
            }
        });
// AJAX HERE

Upvotes: 0

Viktor Kukurba
Viktor Kukurba

Reputation: 1370

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');
  }
});

Upvotes: 1

AersolKing
AersolKing

Reputation: 71

To answer your question, when I submit my forms via ajax I tend not to use submit button.

<input type="submit" value="Ajouter">

to

<input type="button" id="process_form" value="Ajouter">

then you can add some JS functions like

$('#process_form').click ( function (e) {
  if(validate){
    // AJAX HERE
  }else{
    // return errors
  }
});

That should get you moving in the right direction. In your case the form won't submit because you have not supplied a method nor an action. When using Ajax these aren't required though.

Upvotes: 0

Prashant Agrawal
Prashant Agrawal

Reputation: 670

You can do something like this

$.ajax({
    url : 'my_action',
    dataType: 'script',
    beforeSend : function(xhr, opts){
        if(!validate()) //just an example
        {
            xhr.abort();
        }
    },
    complete: function(){
        console.log('DONE');
    }
});

You can check if your data is valid or not and based on it abort ajax request.

Upvotes: 0

Related Questions