Tom Tom - 1 year ago 37
jQuery Question

Form validation with jQuery and AJAX not setting variable correctly

I'm validating a form using Javascript and jQuery.

At the end of the validation function I just AJAX to check an entry against a SQL database to see if it already exists. I have that working fine but I don't seem to be able to update the Javascript variable to indicate whether the check returned that the entry exists or not. Below is a pared down version of the validation function.

At the end when I do the AJAX call if the customer exists, I try to set the isformcomplete variable to false but that doesn't work, it's almost as if it's not reading that line and without that set properly, the form gets erroneously submitted.

What am I missing here? The AJAX call is working properly. Thanks.

<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;

Answer Source

you should always return false in your function

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download