Reputation: 45
I have called a jquery function in form onSubmit if the status is false, then don't allow form submission but currently, it is going to submitted page
here is my whole code php form
echo "<form name='formulaire' id='my_form' method='POST' action='presale_pay.php' onSubmit='return veriftel();'>";
echo "<input type='text' name='promocode' placeholder='Enter Promo Code' id='promo'><div id='result'></div>";
echo "<p> <input type='submit' value='CONFIRM'></form>";
promocheck.php
<?php
include("include/control.php");
if (SessionValide ($session, $bd))
{
$data=array();
$promo=$_POST["promo"];
$party=$bd->ligneSuivante($bd->execRequete("SELECT * FROM promocodes WHERE promocode='$promo' AND used_nbr<=valid_nbr"));
if(!empty($party))
{
$data["status"]=true;
$data["percentage"]=$party["percentage"];
}
else {
$data["status"]=false;
}
echo json_encode($data);
}
?>
function veriftel(e)
{
$.ajax({
type: 'post',
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
if(data.status==false)
{
$("#result").html("<font color=red>Invalid promocode</font>");
return false;
}
else
{
return true;
}
}
});
}
please help me to prevent form submit
Upvotes: 1
Views: 60
Reputation: 1015
should work like this
function veriftel(e)
{
e.preventDefault();
$.ajax({
type: 'post',
async: false,
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
console.log(data);
if(data.status==false)
{
$("#result").html("<font color=red>Invalid promocode</font>");
console.log("false");
return false;
}
else
{
console.log("true");
return true;
}
}
});
}
also the php code should pass the event to the function
echo "<form name='formulaire' id='my_form' method='POST' action='presale_pay.php' onSubmit='return veriftel(event);'>";
Upvotes: 2
Reputation: 1195
The problem is that the following ajax call is asynchronous one. Your code will not wait till you get response from the server, hence the function returns before the completion of ajax call and response.
To avoid the following problem, you'll have to make your ajax call synchronous. Add aysnc:false
to make it syncronous
$.ajax({
type: 'post',
async: false, //syncronous call
url: 'promocheck.php',
data:{promo:$("#promo").val()},
dataType: 'json',
success: function (data) {
}
Please note that making the call synchronous will cause the javascript execution to freeze in the webpage.
Upvotes: 2