user4159594
user4159594

Reputation:

Using jQuery-ajax response with an IF statement

I'm using jquery-ajax to send data to a php. Upon success or failure the php sends back a response. so far everything works fine. Now my questions is how do I use an if statement in jquery to do some action using the response?

See example:

  $.post("php/send.php",
     { 
       email:$( '#email' ).val(),
       name:$( '#name' ).val()
     },
     function(response) {
       alert(response) // shows "Error!"
       if (response != "" || response != "Error!") {
          //do A...
       } else {
          //do B...
       }
   )};

My if statement does not work. Even the response from the php is "Error!" it will //do A.How do I fix this?

Upvotes: 1

Views: 1987

Answers (3)

Danijel
Danijel

Reputation: 12689

The code posted should work if the only output from send.php is something like <?php echo "Error!"; ?>, and, i don't know if it is a typo, but closing brackets for the $.post function should be });

Method 1

Good practice is to use json format ( json_encode() ) for the response, for example:

php

<?php

// if there is an error fill the error data
$response['error'] = 'Error message!';
// else fill the correct data
$response['data'] = [ 'foo' => 'Some data', 'bar' => 'Some other data' ];

header( 'Content-Type: application/json' );
die( json_encode( $response ) );
?>

js

$.post( "php/send.php", { email: $( '#email' ).val(), name: $( '#name' ).val() } )
    .done( function( response ) {
        if ( response.error ) {
            console.log( response.error );
            return;
        }                   
        console.log( response.data );               
    });

Method 2

Alternatively, HTTP response code can be set manually ( http_response_code() ), so that the fail() method of jqXHR object is invoked, like this:

php

<?php

// if case of an error
http_response_code(400);
die( 'Error message!' );

?>

js

$.post( "php/send.php", { email: $( '#email' ).val(), name: $( '#name' ).val() } )
    .done( function( response ) {
        // success
    })
    .fail( function( jqXHR ) {
        console.log( jqXHR.responseText );
    });

Upvotes: 1

jediKnight
jediKnight

Reputation: 786

In your if conditional, the expression to the left of the short-circuit OR (ie. ||) returns true if response is not an empty string. When response = "Error!", ie. not empty, the first part of || becomes true, and //do A will execute. The expression to the right of ||, in this case response != "Error!", is simply ignored when the expression to the left of || is true.

Upvotes: 4

Gumma Mocciaro
Gumma Mocciaro

Reputation: 1215

Usually is not safe to respond with pure text from a php page, i suggest you to use json for the comunication between php and ajax, anyway, your code seems ok, try to add a trim() to the returned string in php

Upvotes: -1

Related Questions