[英]how to implement javascript validation and ajax
我有在提交按钮上必须检查所有验证并同时运行ajax的代码。 我有复杂的代码,但问题在演示代码中显示。
当我要检查有效性并运行ajax时,即使我编写return false并执行提交操作,值也始终为true。
发生这种情况是因为ajax的本质是异步运行。 有人给了我作为链接的解决方案。 如何返回异步调用的响应?
但是我需要代码中的解决方案,所以请解决我的这类问题。 我从一个多月以来就面临这个问题。 我的代码示例如下。
检查javascript.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);
?>
success:function(response) {
if (condition_to_form_submit) {
document.forms.form.submit();
}
}
condition_to_form_submit取决于您的特定需求(可能需要检查一些响应值)
编辑:没看到@Parag Bhayani已经推荐了这种解决方案。 归功于他
function checkValid(){
return new Promise(resolve,reject){
jQuery.ajax({
type: "POST",
dataType: "json",
url:'checkexisting.php',
data:{
companyname: companyname,username: username,
},
success:function(response) {
resolve(); //or reject(err) depend on response data
}
});
}
}
function submitForm(){
document.forms["form"].submit();
}
$('#submitBtn').on('click',function(e){
checkValid().then(submitForm).catch(function(err){
alert(err);
})
}
将提交按钮移到表单外部
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.