The following script shows the error message correctly, but the form always submits whether confirm_shop_code()
returns true
or false
. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false
, but allow it to submit when it returns true
. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
You need to add
async:false
to your ajax codeThe reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning
false
from thesuccess
method of$.ajax
. This is not in the same scope as the parent function and therefore does not also cause the parent function to returnfalse
. So in fact, yourconfirm_shop_code()
function is not returning anything unlesscode
is false and that's why your form is always being submitted, no matter what happens with the AJAX call.I would recommend using jQuery to bind to the form's submit event and just disable form submitting with
preventDefault()
. First, just add anid
attribute to the form (e.g."yourform"
) and do something like: