我具有检查电子邮件是否存在的功能,但是我只想在电子邮件不存在的情况下提交表单

所以我写了以下函数:

$("#form-1").on("submit",function(e){
     e.preventDefault();
    var given_email=document.getElementById("email");

     var data = $("#form-1").serialize();
     $.ajax({
            type : 'POST',
            url  : 'check.php',
            data : data,
            beforeSend: function() {
                $(".submit").val('sending ...');
            },
            success :  function(response) {

                var response = JSON.parse(response);
                if(response.status=='error'){
                  alert("Sorry This Email Already Used ");
                         return false;
                } if(response.status=='true') {
                    return true;
                    $(this).submit();
                }
            }
        });
});


现在如果它返回true,我也不能提交表格。请帮忙。
 我看到了这个问题并回答e.preventDefault doesn't stop form from submitting。但是没有效果


  笔记


即使我尝试过

  if(response.status=='true') { $("#form-1").submit(); } .


但这也行不通

最佳答案

return语句在提交表单之前返回

if(response.status == 'true') {
  //return true; // returns before the form is submitted
  $(this).submit();
  return true; // move return after submit
}


建议

您正在考虑错误的方式,让PHP处理检查并插入后端。

第一个解决方案

在您的PHP中执行类似的操作

$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
  echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
 // insert statement here
 echo json_encode(['message' => 'Submitted']);
}


在你的JS里

$("#form-1").on("submit",function(e){
 e.preventDefault();
var given_email=document.getElementById("email");

 var data = $("#form-1").serialize();
 $.ajax({
        type : 'POST',
        url  : 'check.php',
        data : data,
        beforeSend: function() {
            $(".submit").val('sending ...');
        },
        success :  function(response) {

            var response = JSON.parse(response);
            alert(response.message); // display the message here to the user.
        }
    });
 });


第二解决方案

将表单保存在变量中。

$("#form-1").on("submit",function(e){
 e.preventDefault();

const form = $(this); // get the current form

var given_email=document.getElementById("email");

 var data = $("#form-1").serialize();
 $.ajax({
        type : 'POST',
        url  : 'check.php',
        data : data,
        beforeSend: function() {
            $(".submit").val('sending ...');
        },
        success :  function(response) {

            var response = JSON.parse(response);
            if(response.status=='error'){
              alert("Sorry This Email Already Used ");
                     return false;
            } if(response.status=='true') {
                form.submit(); // submit the form here
                return true;
            }
        }
    });
});

关于javascript - e.PreventDefault和ajx提交无法一起使用[return true]不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55881313/

10-12 16:26
查看更多