这是我的validate()函数,返回true或false。
我的问题是,仅当validate()返回true时,我才想调用ajax提交表单代码,否则它将显示带有错误消息的警报,提示无效数据并停留在页面中,而无需提交表单,而无需使用ajax,我知道我可以使用如果为true,则返回document.form2.submit();但在我的情况下,它不起作用,请帮忙!
Ajax代码:
$("#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 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 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>
最佳答案
您可以使用preventDefault阻止提交表单。并使用条件,如果validate返回true,则使用Ajax其他情况显示警报
$("#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');
}
});