Ibrahim
Ibrahim

Reputation: 9

where is the error in my if statement code?

I have a problem that I send a request to a page and when I get the response which is a string something get wrong

This is the code request :

 jQuery.ajax({
     url:'../admin/parsers/check_address.php',
     method:'post',
     data :data,//data that is been requested   
     success:function(data){
         if(data != 'passed'){

             jQuery('#payment-errors').html(data);
         }
         if(data=='passed'){
            alert(data);
         }
     },//this data is which is coming back from response
     error:function(){alert('حدث خطأ ما');},

 });

and this is the code of the response :

echo 'passed';

even though the response contains the string 'passed' but it does not go into the if statement

if(data=='passed'){
                alert(data);
             }

so where is the fault in my code and thank you in advance

Upvotes: 0

Views: 39

Answers (2)

Your answer should be a JSON object, not a string. Try to do the following:

In your PHP program:

echo json_encode(array('resp' => 'passed'))

In your Javascript code:

if(data.resp != 'passed'){
    jQuery('#payment-errors').html(data.resp);
}
    alert(data.resp);
}

By the way, if something is not != then it is ==. You may surely simplify your else condition as I did.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Good possibility there is some extra whitespace at either end of the string also (due to whitespace in php file)

Try trimming the response:

if(data.trim() == 'passed'){

In general it is easier to use JSON than strings for such requests

Upvotes: 1

Related Questions