javascriptphpajaxresponsetext

How do I set ajax responseText to be equal to string?


I have a problem with ajax.responseText in condition where it has to be equal to string which is passed in from php echo from external file, the thing is that the string seems not to be equal to ajax.responseText,

but if alert(ajax.responseText) it is exactly the string "friend_request_sent"

function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $u; ?>.");

if(conf != true){
    return false;
}   
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "friend_system.php");

ajax.onreadystatechange = function() {
    if(ajaxReturn(ajax) == true) {

        if(ajax.responseText=="friend_request_sent"){          
            _(elem).innerHTML = 'OK Friend Request Sent';       
        } else if(ajax.responseText == "unfriend_ok"){
            _(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';       
        } else{        
            alert(ajax.responseText);
            _(elem).innerHTML = 'Try again later';
        }
    }
}
ajax.send("type="+type+"&user="+user);

}

now the code im getting from friend_system.php

 ...{ 
 echo"friend_request_sent";
 exit();
 }

and the ajax js code

function ajaxObj( meth, url ) {
 var x = new XMLHttpRequest();
 x.open( meth, url, true );
 x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 return x;
}
function ajaxReturn(x){
   if(x.readyState == 4 && x.status == 200){
    return true;    
 }

} the third condition is where it struggles ,it always goes to else, why?


Solution

  • To check ajax response against any string, it is better to trim the response text

    request.responseText.trim() === "string"