I have code on which on submit button I have to check all validation and simultaneously run ajax. I have complex code but problem is shown in demo code.
When I am going to check validation and run ajax then value goes always true even if I write return false and submit action is perform.
This is happening because nature of ajax which run asynchronously. And some one has given me solution as link How do I return the response from an asynchronous call?
But I need solution in code So please solve my this type of problem. I am facing this problem from more than one month. My code sample is below.
checkjavascript.php
<?php
if(isset($_POST['submit'])){
die("lokesh");
}
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function checkjs(){
if(document.getElementById('a').value==""){
alert("insert a");
return false;
}
if(document.getElementById('b').value==""){
alert("insert b");
return false;
}
if(document.getElementById('c').value==""){
alert("insert c");
return false;
}
var companyname = document.getElementById('b').value;
var username = document.getElementById('c').value;
jQuery.ajax({
type: "POST",
dataType: "json",
url:'checkexisting.php',
data:{
companyname: companyname,username: username,
},
success:function(response) {
alert(response);
return false;
//$( "#lokeshform" ).submit();
//jQuery( "#lokeshform" ).submit();
document.forms.form.submit();
}
});
}
</script>
</head>
<body>
<form action="#" method="post" name="form" id="lokeshform" onsubmit="return checkjs();">
<input type="text" id="a">
<input type="text" id="b">
<input type="text" id="c">
<input type="submit" name="submit">
</form>
</body>
</html>
checkexisting.php
<?php
$companyname = $_REQUEST['companyname'];
$username = $_REQUEST['username'];
$response = $companyname.$username;
echo json_encode($response);
?>