使用jQuery和AJAX进行表单验证无法正确设置变量

时间:2017-07-26 13:34:06

标签: jquery ajax validation

我正在使用Javascript和jQuery验证表单。

在验证函数结束时,我只需要AJAX来检查SQL数据库的条目,看它是否已经存在。我的工作正常,但我似乎无法更新Javascript变量以指示检查是否返回该条目是否存在。以下是验证功能的简化版本。

如果客户存在,当我进行AJAX调用时,我会尝试将isformcomplete变量设置为false,但这不起作用,它几乎就像它不读取一样该行没有正确设置,表单会被错误地提交。

我在这里缺少什么? AJAX调用正常工作。感谢。

<form method="post" action="../../../scripts/create-customer.asp" id="create-customer" onsubmit="return create_customer();">

function create_customer()
{
    var isformcomplete = true;
    message = "The following tasks need to be completed before continuing:\n\n";
    if ( $("#customerno").val() == "" )
    {
        message += "* Select the customer's country and enter its unique identifier\n";
        isformcomplete = false;
    }
    if ( $("#product").val() == "" )
    {
        message += "* Select a product\n";
        isformcomplete = false;
    }

    if (isformcomplete == false)
        { alert(message); }
    else
    {
        $("#alertsDynamic").slideUp();
        $.post("/global-marketing/scripts/check-new-customer.asp",{ fromsubmit: true, customer: $("#customerno").val()+"|"+$("#product").val()}, 
        function(data, status)
            {
                if ( data == "true" )
                {
                    $("#error-message").html($("#customerno").val()+" "+$("#product").val()+" already exists");
                    $("#alertsDynamic").slideDown();
                    isformcomplete = false;
                }
            }
        );
    }
    return isformcomplete;

1 个答案:

答案 0 :(得分:3)

你应该总是在你的函数中返回false

function create_customer()
{
  message = "The following tasks need to be completed before continuing:\n\n";
  if ( $("#customerno").val() == "" )
  {
    message += "* Select the customer's country and enter its unique 
               identifier\n";
    isformcomplete = false;
}
if ( $("#product").val() == "" )
{
    message += "* Select a product\n";
    isformcomplete = false;
}

if (isformcomplete == false)
    { alert(message); }
else
{
    $("#alertsDynamic").slideUp();
    $.post("/global-marketing/scripts/check-new-customer.asp",{ fromsubmit: true, customer: $("#customerno").val()+"|"+$("#product").val()}, 
    function(data, status)
        {
            if ( data == "true" )
            {
                $("#error-message").html($("#customerno").val()+" "+$("#product").val()+" already exists");
                $("#alertsDynamic").slideDown();
                // Here you need to send the form in case every thing is fine

            }else{
                $("form").submit();
            }
        }
    );
}
return false;