Search code examples
javascriptjquerystring-comparison

Jquery comparing strings not working in POST


I have a jquery post code that can have two different reactions based on the response. if the response is a then i would like to alert() if it is not a then i would like to update a div (ratebox). However, one of the lines (below) isn't working. It appends the letter a onto the ratebox when it should bring up the alert. I checked that answerrating.php does produce the letter a.

JQUERY:

$.post('../answerrating.php' , {answer_id: answer_id , direction: 2} , function(response){
        if (response == 'a'){  //this line doenst work
            alert("error");
        }
        else {
            ratebox.text(response);
            }
        });

Solution

  • Perhaps you get some whitespaces in the response, try using jQuery.trim():

    if ($.trim(response) == 'a'){  //this line doenst work
       alert("error");
    }
    

    You could also use firebug to check so that your response don't include any html.

    If you are getting something other than plain text from the server try setting the dataType in your call:

    $.post('../answerrating.php',
      {
        answer_id: answer_id, 
        direction: 2
      }, 
      function (response) {
        //this line doenst work
        if (response == 'a') {
          alert("error");
        } else {
          ratebox.text(response);
        }
      },
      dataType: 'text'
    );