我有一个表单提交页面,当提交表单时我需要调用Ajax。但是现在Ajax没有用。我的主页是add_sale.php,Ajax页面是ajx_check_sale.php
我的代码:
add_sale.php
function validate_form()
{
var cust_name= $('#cust_name').val();
var total= $('#total').val();
var sale_type= $('#sale_type').val();
if(sale_type=='return')
{
$.ajax({
type: "POST",
url: 'ajx_check_sale.php',
data:'cust_name='+cust_name + '&total=' + total,
success: function(msg)
{
alert(msg);
/*if(msg==0)
{
alert("Return is greater then sale");
return false;
} */
}
});
}
}
<form action="" method="post" name="adFrm" onSubmit="return validate_form()">
</form>
ajx_check_sale.php
require_once("codelibrary/inc/variables.php");
require_once("codelibrary/inc/functions.php");
echo $cust_name=$_POST['cust_name'];
echo $return=$_POST['total'];
$cus="select sum(total) as total_sum from customer where id='$cust_id'";
$cus2=mysql_query($cus);
$fet=mysql_fetch_array($cus2);
$total=$fet['total_sum'];
if($return>$total)
{
$status=0;
echo $status;
}
else
{
$status=1;
echo $status;
}
答案 0 :(得分:1)
如果您熟悉jquery,则在表单提交事件上使用 event.preventDefault()函数,以便不会发生表单提交。这是一个示例:
$(form).submit(function(event){
event.preventDefault();
})
答案 1 :(得分:0)
也许像这样......
<script type="text/javascript">
function validate_form()
{
var cust_name= $('#cust_name').val();
var total= $('#total').val();
if(sale_type=='return') //what is variable sale_type here ?please define
{
$.ajax({
type: "POST",dataType:"json",
url: 'ajx_check_sale.php',
data:'cust_name='+cust_name + '&total=' + total,
success: function(msg)
{
if(msg.status==0)
{
alert("Return is greater then sale");
}
return false;
}
});
}else{
return false; //or alert("someth went wrong)
}
}
</script>
<form action="" method="post" name="adFrm" onSubmit="return validate_form()">
</form>
和ajx_check_sale.php
$data = $_POST;
//.......
if($return>$total)
{
echo json_encode(array('status'=>0));
}
else
{
echo json_encode(array('status'=>1));
}
答案 2 :(得分:0)
function validate_form(){
var cust_name= $.trim($('#cust_name').val());//remove spaces
var total= $.trim($('#total').val());//remove spaces
if(sale_type=='return')
{
$.ajax({
type: "POST",
url: 'ajx_check_sale.php',
data:{ cust_name : cust_name , total: total},//you can use this format, instead of passing the way you were doing
success : (function(msg){//Success part of the ajax
alert(msg);
/*if(msg==0){
alert("Return is greater then sale");
return false;
} */
}),
error : (function(msg){//This part will run if there is any error from the API
//error part
})
});
}
}