Reputation: 9
I have a form submit page, when the form is submitted I need to call Ajax. But now Ajax is not working. My main page is add_sale.php and the Ajax page is ajx_check_sale.php
My code :
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;
}
Upvotes: 0
Views: 80
Reputation: 328
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
})
});
}
}
Upvotes: 0
Reputation: 672
maybe smth like this
<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>
and the ajx_check_sale.php
$data = $_POST;
//.......
if($return>$total)
{
echo json_encode(array('status'=>0));
}
else
{
echo json_encode(array('status'=>1));
}
Upvotes: 0
Reputation: 1821
If you are familiar with jquery then use event.preventDefault() function on form submit event so that form submission will not happen. Here's is a sample:
$(form).submit(function(event){
event.preventDefault();
})
Upvotes: 1