I have a simple php file:

<?php
/**
* email_validation_query: evq.php
* This file is placed in the root directory and returns the owner's email address
* in the jos_owners table along with the animal's name and the breeder who registers them.
**/
$user_name = "user_name";
$password = "password";
$server = "localhost";
$email=$_GET['email'];
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL="SELECT cf_user_id,petname FROM jos_owners WHERE email='".$email."'";
$result = mysql_query($SQL);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
$users='';
$petnames='';
while($data = mysql_fetch_array($result)){
  if(!empty($users)){
    $users.=',';
    $petnames.=',';
  }
  $users.=$data['cf_user_id'];
  $petnames.=$data['petname'];
}
echo $users.'|'.$petnames;
mysql_close($db_handle);
?>

My form is part of a chronoforms joomla addon with custom code:

<!--
  'owners.php'
  26th August 2014
-->
<?php
  // Get user-information from Joomla
  $user = &JFactory::getUser();
  $form->data['breederemail'] = $user->email;
?>
<img id="processing_image"
   style="visibility: hidden; position: absolute; float: left; left: 560px; top: 500px;"
   src="images/wait.gif" />
<script type="text/javascript">
var userid=<?php echo $user->id;?>;
window.onload = function(){
  initform();
}
function initform() {
  document.owners.onsubmit=breeders_form_validation;
}
function breeders_form_validation(){
  var response=validate_email();// always false, why?
  if(response){
    var wait=document.getElementById('processing_image');
    wait.style.top=findTop(document.getElementById('submit'))-100+'px';
    wait.style.visibility="visible";
  }
  return response;
}
function validate_email() {
  var owners_email=document.getElementById('email').value;
  if(ajaxCheck(owners_email)){// always false, why?
    // never gets here
    return true;
  }
  return false;
}
function ajaxCheck(owners_email){
  var ajaxRequest;  // The variable that makes Ajax possible!
  try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
  } catch (e){
    // Internet Explorer Browsers
    try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try{
        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e){
        /* Something went wrong, we can't interrogate the database because the
        browser doesn't support AJAX. So we have to allow the user to submit possible
        duplicates*/
        return true;
      }
    }
  }
  ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
      var responseText=ajaxRequest.responseText;
      var petsarray=responseText.split('|');
      var userarray=petsarray[0].split(',');
      var petnames=petsarray[1].split(',');
      for(var i=0;i<userarray.length;i++){
        if(userarray[i]==userid){
          if(document.getElementById('petname').value==petnames[i]){
            alert('You cannot submit the same owner and pet twice!');
            return false;
          }
        }
      }
      return true;// this should be true, but it isn't. why?
    }
  }
  owners_email=encodeURI(owners_email);
  ajaxRequest.open("GET", "evq.php?email="+owners_email, true);
  ajaxRequest.send(null);
  return false;
}
function findTop(element) {
  if (element) {
    var parentPos = findTop(element.offsetParent);
    return parentPos + element.offsetTop;
  } else {return 0;}
}
</script>

My form never submits; it always evaluates to false.

The php script returns the user id and petname as a string containing the comma deliminated strings of the ids and petnames separated by a pipe. I split both of these into an ID array and a Petnames array, which I search to see that the ID of the user has not submitted the same pet already. If he has, the function returns false with an error message. Otherwise it should return 'true'.

But it always returns 'false'.

Damn, sorry, pretty stupid of me.

Obviously the 'onreadystatechange' function is a function.

Therefore it's not called inside the 'ajaxCheck' function.

So even if it returns 'true' there's nothing to pass the returned value to.

Can anyone suggest an alternative way to do this.

Ok, I've ammended my code:

var owner_duplicated=1;//<-------Global variable initialising owner duplicated
var owners_email='';//<----------Global variable
window.onload = function(){
  initform();
}

function initform() {
  document.owners.onsubmit=breeders_form_validation;
  document.getElementById('email').onblur=checkDB;
}

function checkDB(){
  owners_email=document.getElementById('email').value;//<----Set Global variable
  ajaxCheck();//<----Run Ajax on field losing focus.
}



function ajaxCheck(){
  var ajaxRequest;  // The variable that makes Ajax possible!
  try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
  } catch (e){
    // Internet Explorer Browsers
    try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try{
        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e){
        /* Something went wrong, we can't interrogate the database because the
        browser doesn't support AJAX. So we have to allow the user to submit possible
        duplicates*/
        owner_duplicated=0;
        return true;// never returns true. Why not?
      }
    }
  }
  ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
      var responseText=ajaxRequest.responseText;
      var petsarray=responseText.split('|');
      var userarray=petsarray[0].split(',');
      var petnames=petsarray[1].split(',');
      var number_of_entries=0;//<-------------- The user is allowed 2 entries with the same owner.
      owner_duplicated=0;//<---------- Initialised as no duplicates
      for(var i=0;i<userarray.length;i++){
        if(userarray[i]==userid){
          number_of_entries++;
          if (number_of_entries>1){
            owner_duplicated=2;//<---- changed to 2 if used twice already
          }
        }
      }
    }
  }
  owners_email=encodeURI(owners_email);
  ajaxRequest.open("GET", "evq.php?email="+owners_email, true);
  ajaxRequest.send(null);
}

All well and good.

When the text box loses focus, the owners_email variable is set and the php serverside interrogates the DB for existing owners bearing the same email. The information is returned in a string comprising 2 comma-deliminated strings separated by the pipe | character, containing the user ids in the first and the petnames in the second.

If the same user has already entered the owner twice, then the 'owner_duplicated' variable is now set to 2.

function breeders_form_validation() {
  if(owner_duplicated==2){//<------------- if the user has already used this owner twice, the onsubmit returns false.
    document.getElementById('errmsge').innerHTML="<p>You cannot register this owner more than twice!</p>";
    valerr.style.visibility="visible";
    return false;
  }
  return true;//<----- if the owner isn't dulplicated it returns true and the form is submitted.
}

Works reasonably well when the email textbox loses focus to another textbox.

However, if the focus is lost because the 'submit' button is pressed, then the form is not submitted. It is only submitted after the 'submit' button is pressed a second time.

I've refined the code a bit:
evq.php:

$email=$_GET['email'];
$userID=$_GET['ID'];
//echo $email.'+'.$userID.';';
$email=rawurldecode($email);
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$SQL="SELECT cf_user_id,petname FROM jos_owners WHERE email='".$email."'";
$result = mysql_query($SQL);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header('Content-type: text/html; charset=utf-8');
$owner_count=0;
while($data = mysql_fetch_array($result)){
  if($userID==$data['cf_user_id']){
    $owner_count++;
  }
  if($owner_count>1){
    break;
  }
}
if($owner_count<2){// If there's only one entry, the user can have another one.
  $owner_count=0;
}
echo $owner_count;//<-----The owner count is returned.
mysql_close($db_handle);

The Javascript is as follows:

<div id="validation_error"
   style="visibility: hidden; opacity: 1; position: absolute; float: left; left: 560px; top: 500px;"
   class="fc-tbx">
   <table border="0" cellpadding="0" cellspacing="0">
     <tbody>
       <tr><td class="tl"></td><td class="t"></td><td class="tr"></td></tr>
       <tr><td class="l"></td>
       <td class="c">
         <div class="err" id="errmsge"><p>Please use the new owner's email rather than your own.</p></div>
         <a class="close" onclick="hidedialog()"></a>
       </td>
       <td class="r"></td></tr>
       <tr><td class="bl"></td><td class="b"></td><td class="br"></td></tr>
     </tbody>
   </table>
 </div>
<img id="processing_image"
   style="visibility: hidden; position: absolute; float: left; left: 560px; top: 500px;"
   src="images/wait.gif" />
<script type="text/javascript">
var userid=<?php echo $user->id;?>;
var owner_duplicated=1;
var owners_email='';
window.onload = function(){
  initform();
}
function initform() {
  document.owners.onsubmit=breeders_form_validation;
  document.getElementById('email').onblur=checkDB;
}
function breeders_form_validation(){
  var response=validate_email();
  if(!response){
    return false;
  }
  document.getElementById('processing_image').style.visibility="visible";
  return true;
}

function validate_email() {
  if(owner_duplicated==2){
    document.getElementById('errmsge').innerHTML="<p>You cannot register this owner more than twice!</p>";
    valerr.style.visibility="visible";
    return false;//<--- Does not submit if owner already registered twice.
  }
  return true;
}
function checkDB(){
  owners_email=document.getElementById('email').value;
  ajaxCheck();
}
function ajaxCheck(){
  var ajaxRequest;  // The variable that makes Ajax possible!
  try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
  } catch (e){
    // Internet Explorer Browsers
    try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try{
        ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e){
        /* Something went wrong, we can't interrogate the database because the
        browser doesn't support AJAX. So we have to allow the user to submit possible
        duplicates*/
        owner_duplicated=0;
        return true;
      }
    }
  }
  ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
      owner_duplicated=ajaxRequest.responseText;
      //alert(owner_duplicated);
    }
  }
  owners_email=encodeURI(owners_email);
  ajaxRequest.open('GET', 'evq.php?email='+owners_email+'&ID='+userid, true);
  ajaxRequest.send(null);
}
function findTop(element) {
  if (element) {
    var parentPos = findTop(element.offsetParent);
    return parentPos + element.offsetTop;
  } else {return 0;}
}
function findLeft(element) {
  if (element) {
    var parentPos = findLeft(element.offsetParent);
    return parentPos + element.offsetLeft;
  } else {return 0;}
}
</script>

Seems to work ok.

Just adding this to help others, but if anyone can suggest improvements, by all means do.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.