Search code examples
phpjavascriptajaxlogicresponsetext

ResponseText that comes back from ajax is not equal to php text


Heres the issue. I have an an ajax function that is just checking if an email that a user inputs is already used.

The php script that it uses either sends back "true" or "false" strings depending on the result. When i get the response text back, or the "data" variable in the below function, and see if its == to "true" it never passes and always evaluates to false.

This is odd, because when I have printed out the data variable on screen it shows as "true" when it should, but its just not being shown as equal to "true" in the if statement. No idea what is happening here.

AJAX FUNCTION:

function check_email() {
  var email = document.sign_up_form.email_first.value;
  document.getElementById("email1").innerHTML = ' <img src="loading.gif" width="15">';
 $.ajax({
        type: "GET",
        url: "java_check_email.php",
        data: "email="+email,
        success: function(data){
              if(data == "true"){
              document.getElementById("email1").innerHTML = ' <img src="check.png" width="15">';
              document.getElementById("email4").innerHTML = '';  
              }
              else {
              document.getElementById("email1").innerHTML = ' <img src="xmark.png" width="15">';
              document.getElementById("email4").innerHTML = 'Email is already in use<br>';    
              }
     }
});

}

UPDATE:

PHP script looks like this

    <?php
include('functions.php');

$email = $_GET['email'];

$query_check = "removed for obvious reasons...";

$result_check = mysql_query($query_check);

if(mysql_num_rows($result_check) == 0){
echo 'true';
}
else{
echo 'false';
}

?>

Also, after calling console.log(data) when the ajax response is received i got a value of "true" in the js console.....


Solution

  • For debugging, try

    if (data.replace(/\s+/g, '') == "true") {
    

    ...my money is on whitespace outside the <?php ?> tags. Note that if this solves the problem it should not considered the solution - the real solution is to remove the additional whitespace from the PHP script.

    The < of the opening <?php tag should be the very first character in the file. For example:

              This empty line will be output directly
        <?php
    ^^^^ This whitespace will be output directly
    

    Note also that the closing ?> tag is often unnecessary (as it seems to be in this case) and omitting it completely can help avoid problems like this.

    If you want to return a boolean to JS you should simply echo 1 or 0, so you can just do this in the receiving Javascript:

    if (data) {