0

My head is about to explode. I cannot figure out what is going on here. Below is my code for handling a ajax request.

 xmlhttp_DELrep.onreadystatechange = function(){
    if(xmlhttp_DELrep.readyState == 4 && xmlhttp_DELrep.status == 200){

        if(xmlhttp_DELrep.responseText == 'delete_ok'){
            document.getElementById(replyboxID).style.display='none';
            console.log('delete success!');
        }else{
            console.log('delete fail');
            console.log('xmlhttp_DELrep.responseText: '+ xmlhttp_DELrep.responseText);
        }
    }
}

This is the response that I am getting through the console:

 delete fail
 xmlhttp_DELrep.responseText: delete_ok

I do not understand why my first 'if' statement is not executing given that the xmlhttp_DELrep.responseText does indeed equal 'delete_ok' - as shown in the console. Please can someone help?

dave
  • 475
  • 6
  • 17
  • 3
    Maybe there's whitespace somewhere. Try `console.log("'" + xmlhttp_DELrep.responseText + "'");`. –  Aug 15 '15 at 11:08
  • I face you're receiving the response from a server-side scripts. If you do not have to use the response as output, I recommend you to use numbers (200 = OK, 404 = not found, and so on) It will make the application easier to maintain – Cliff Burton Aug 15 '15 at 11:30
  • @torazaburo, you were right. using your code I discovered that whopping white spaces were introduced some where to the right of my xmlhttp_DELrep.responseText. I used trim() to get rid of them and everything works as it should. If you put your response as an answer I could accept it. Thanks a lot! – dave Aug 15 '15 at 12:44

2 Answers2

1

You may have white spaces to the right of the text response, which you cannot see in your console output. Your code will work properly if you trim them away with trim().

  • Do you know why or how these white spaces are introduced? In my cases lines and lines of white spaces were present on the right side of my string. – dave Aug 15 '15 at 13:03
0

I don't know if it would solve your issue, but i would try different ways of comparing the strings.

As found in the references below, you could use:

string_a.localeCompare(string_b);

/* 
    Returns:
    0:  exact match
   -1:  string_a < string_b
    1:  string_b > string_b
*/

Another issue could be white spaces that are not visible in console output.

if(xmlhttp_DELrep.responseText.trim() == 'delete_ok') { ... }

References:

https://stackoverflow.com/questions/2167602/optimum-way-to-compare-strings-in-javascript

Community
  • 1
  • 1
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – xShirase Aug 15 '15 at 13:05
  • 1
    @xShirase I added the information relevant from the link to the answer. – Alexander Fuchs Aug 15 '15 at 14:20