Sefam
Sefam

Reputation: 1773

Javascript condition not working in AJAX callback

I am having a small problem here with an IF condition in an ajax callback:

$.ajax(
        {
            type: "POST",
            url: "AjouterAttribut.php",
            data: { val: Valeur, table: Attribut }
        }).done(function(message)
        {
            if (message == '-')
            {
                alert("test");
            } else {
                alert(message);
                var Tableau = jQuery.parseJSON(message);
                $this.prev().find('option').remove();

                for (var i=0; i< Tableau.length; i++)
                {
                $this.prev().append("<option value="+ Tableau[i][0] +">" + Tableau[i][1] + "</option>");
                }
            }
        });

The problem is that when the ajax function does send back '-' in message, it goes right past the if into the else, and alerts '-'. What is going on?

Upvotes: 1

Views: 234

Answers (1)

Lazerblade
Lazerblade

Reputation: 1127

Try wrapping your message in start / end identifiers to check for white space, or trim the message before the if statement.

$.trim(message);

alert('|' + message + '|');

You may also get more mileage out of your time by using the console instead of alerts.

console.log(message);

Works in Chrome, Firefox, Safari. For testing, it's my preferred method.

Upvotes: 1

Related Questions