使用ajax和jquery防止表单提交根据条件ajax
问题描述:
我已经提交表单使用php,ajax和jquery.I要防止表单提交根据ajax条件。但不stoppng提交表单。任何机构给任何解决方案对于这些问题? 下面使用ajax和jquery防止表单提交根据条件ajax
<script>
function validate_form()
{
var sale_type= $('#sale_type').val();
var cust_name= $('#cust_name').val();
if(sale_type=='credit')
{
alert("msg");
$.ajax({
type: "POST",
url: 'ajx_validation_due_date.php',
data:'cust_name='+cust_name,
success: function(msg)
{
alert(msg);
if(msg==0)
{
alert("You cant add sale,Due days is completed");
preventDefault();
return false;
}
}
});
}
}
</script>
<form action="" method="post" name="adFrm" onSubmit="return validate_form()">
</form>
答
我的代码被赋予通常Ajax是异步调用。
在ajax调用中使用“异步”。脚本会一直等到ajax调用完成。
$.ajax({
type: "POST",
url: 'ajx_validation_due_date.php',
data:'cust_name='+cust_name,
async : false,
success: function(msg)
{
// Your code
}
});
或者您可以验证在提交后你的PHP一样..
答
的问题是,你的代码将进一步运行,而无需等待Ajax调用来完成,返回undefined
,因此表单提交会发生。
取而代之的是,使用event.preventDefault()
防止默认表单提交,然后手动提交。
<form action="" method="post" name="adFrm" onSubmit="validate_form(event)">
function validate_form(event) {
event = event || window.event;
event.preventDefault(); // prevent submission
var sale_type = $('#sale_type').val();
if (sale_type == 'credit') {
alert("msg");
$.ajax({
type: "POST",
url: 'ajx_validation_due_date.php',
data: 'cust_name=' + cust_name,
success: function (msg) {
alert(msg);
if (msg == 0) {
alert("You cant add sale,Due days is completed");
return false;
}
else
$("[name='adFrm']")[0].submit(); // submit the form manually upon success
}
});
}
}
答
你也可以像下面这样做。 SOURCE
<form action="" method="post" name="adFrm" id="adFrm" >
</form>
$("#adFrm").submit(function(e)
{
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit ,
// and if you again submit , it won't go through this process again.
var sale_type = $('#sale_type').val();
if (sale_type == 'credit') {
alert("msg");
$.ajax({
type: "POST",
url: 'ajx_validation_due_date.php',
data: 'cust_name=' + cust_name,
success: function(msg) {
alert(msg);
if (msg == 0) {
alert("You cant add sale,Due days is completed");
return false;
}
else
$("#adFrm").submit(); // note: i have unbinded the submit, so it will simply submit, instead of going through all
}
});
}
});
什么是'cust_name'? 'msg'的价值是什么? – 2014-10-08 05:42:18
我有cust_name值,我忘了添加它,味精值是0 – 2014-10-08 05:47:35