palsikh
palsikh

Reputation: 3

how to compare ajax response text with some string without jQuery

I am trying to get a value back through if it found value in database sends/echo result value in it does found sends back/echo 'not_found'.

When I try to compare in the following script it always goes inside if, and never goes to else.

I also tried NULL, FALSE instead not_found does not work.

function showHint(str) {
    var xmlhttp;
    var url=  "check_album.php?q="+str;
    document.getElementById("txtHint1").innerHTML=(url);
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            if(xmlhttp.readyState.responseText !='not_found') {
                document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
            } else {
                document.getElementById("txtHint3").innerHTML='no result';}
            }
        }
        xmlhttp.open("GET",url,true);
        xmlhttp.send();
    }
}

and this is check_album.php code which sending result back

    require_once('../php/classes/class.add_album.php');
    if ($_SERVER["REQUEST_METHOD"] == "GET") {
       $album_name = $_GET["q"];

      //make new object
      $objfile = new add_album();

      //call object method with post method value we got and save result in result 
      $file_found=$objfile->find_album($album_name);

      if ($file_found)echo $file_found;
      else         echo 'not_found';
     }

Upvotes: 0

Views: 1731

Answers (2)

R D
R D

Reputation: 1332

This is because response text may have unwanted spaces Try to trim that response

String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};

if(xmlhttp.responseText.trim() !='not_found' ){
    document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
}else{
    document.getElementById("txtHint3").innerHTML='no result';
}

Upvotes: 1

Jay Bhatt
Jay Bhatt

Reputation: 5651

Try this.

 if(xmlhttp.responseText !='not_found' ){
        document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
  } else
  {
        document.getElementById("txtHint3").innerHTML='no result';
  }

Upvotes: 2

Related Questions