Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong result string compare jquery

I'm getting wrong string compare result in my ajax function:

$("#scan").click(function() {
    id = 1;

    $.ajax({ 
        type: "POST",
        data: { reqValue: id },
        url: "http://localhost:8080/test-notifier-web/RestLayer",
        success: function(data){        
            $.trim(data)
            alert(data);
            if ('OK' === data) {
                alert("yes");
            } else {
                alert("no");
            }
        }
    });
});

Data is returned from my Java servlet response, in fact i get an alert displaying "OK", then it shows me "no". What am I doing wrong?

like image 648
slash89mf Avatar asked Mar 13 '26 10:03

slash89mf


1 Answers

You're calling $.trim() but not assigning the result to anything. Try trimming whitespace from the returned string before you compare, like this:

$("#scan").click(function() {
    id = 1;

    $.ajax({ 
        type: "POST",
        data: { reqValue: id },
        url: "http://localhost:8080/test-notifier-web/RestLayer",
        success: function(data) {      
            if ('OK' === data.trim()) {
                alert("yes");
            } else {
                alert("no");
            }
        }
    });
});

It's for this reason that returning a string from an AJAX request isn't a good idea. Look in to returning JSON instead.

like image 96
Rory McCrossan Avatar answered Mar 15 '26 23:03

Rory McCrossan