Link to home
Start Free TrialLog in
Avatar of PIComponents
PIComponentsFlag for United States of America

asked on

PHP AJAX duplicate check

With the code included, I am trying to detect if the entered customer id already exists in the database. If it does, I want to display an error message.  This process is working fine through the CheckForDuplicateCustomerStateChanged function. This function is getting the XML from the PHP page. I have verified that the correct brach of the IF is executing by putting alert statements the different branches. The problem is, when control returns back to the SaveCustomer functio (after the call to CheckForDuplicateCustomer), the value of the variable isUnique is always false.

What am I doing wrong?
var isUnique = new Boolean(false);
 
function SaveCustomer()
{
    txtCustomerId = document.getElementsByName("txtcustomerid")[0];
    isUnique = false;
    if (txtCustomerId.value == "")
    {
      errorText = document.getElementById("idError");
      document.getElementById("idError").innerHTML = "The Customer Id is required.";
      errorText.style.visibility="visible";
    }
    else
    {
      custPk = document.getElementsByName("txtid")[0].value;
      CheckForDuplicateCustomerId(txtCustomerId.value, custPk)
      if (!isUnique) 
      {
        errorText = document.getElementById("idError");
        document.getElementById("idError").innerHTML = "The Customer Id is not unique.";
        errorText.style.visibility="visible";
      }
      else
      {
        document.editcustomerform.submit()
      }
    }
}
 
function CheckForDuplicateCustomerId(custId, custPk)
{
  xmlHttp=GetXmlHttpObject()
  if (xmlHttp==null)
  {
    alert ("Your browser does not support HTTP Request");
    return;
  }
  var url="getcustomerbycustid.php";
  url=url+"?customerid="+custId+"&custpk="+custPk;
  xmlHttp.onreadystatechange=CheckForDuplicateCustomerIdStateChanged; 
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}
 
function CheckForDuplicateCustomerIdStateChanged()
{
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
  {
    var responseValue = parseInt(xmlHttp.responseXML.text);
    if (responseValue == -1)
    {
      alert("An error occured while checking the customer id. Please try again.");
    }
    else if (responseValue == 0)
    {
      isUnique = true;
    }
    else
    {
      isUnique = false;
    }
  }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of LordOfPorts
LordOfPorts
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of PIComponents

ASKER

BINGO! That's what I was looking for!