Martin Muehl
Martin Muehl

Reputation: 104

use $.ajax() response for if else statement

I just can't get it to work that I'm using the response of an ajax call in an if/else statement. If I output the response in console.log() it shows that it is correctly set, but the simple if/else statement just doesn't work.

function check_foo() {
dataString = {action: 'do_this'};

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: dataString,
    success: function(foo) {
        console.log('foo='+foo); // output: foo=ok

        if (foo=="ok") { // should be true, but isn't
           console.log('foo='+foo+' -> OK');
        } else { // instead this gets output
           console.log('foo='+foo+' -> FAIL'); // output: foo=ok -> FAIL
        }
    }
});
}

check_foo();

ajax.php:

echo 'ok'; // This is the result of the call

so foo is correctly set as 'ok' (as shown in console.log), but the if/else doesn't seem to recognize it...

Any help would be very much appreciated!

Upvotes: 1

Views: 3696

Answers (2)

ahPo
ahPo

Reputation: 384

Tried with this code

<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Stack Tester</title>
  <script src=jquery.min.js type="text/javascript"></script>
  <script type="text/javascript">
     //<![CDATA[
        function check_foo() {
            dataString = {action: 'do_this'};
            $.ajax({
                type: "POST",
                url: "ajax.php",
                data: dataString,
                success: function(foo) {
                    console.log('foo='+foo); // output: foo=ok
                    if (foo=="ok") { // should be true, but isn't
                        console.log('foo='+foo+' -> OK');
                    } else { // instead this gets output
                        console.log('foo='+foo+' -> FAIL'); // output: foo=ok -> FAIL
                    }
                }
            });
        }
     //]]>
  </script>
</head>
<body>
  <script type="text/javascript">
      //<![CDATA[
        check_foo();
      //]]>
  </script>   
</body>
</html>

with ajax.php

<?php
echo 'ok';

and it worked fine.

version of jquery.min.js is 1.7.1

Upvotes: 0

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

@johan comment is perfect answer for you i have tried it like:- use trim() function.js:-

function check_foo() {
dataString = {action: 'do_this'};

jQuery.ajax({
    type: "POST",
    url: "response.php",
    data: dataString,
    success: function(foo) {

        if (jQuery.trim(foo) == "ok") { 
           alert(foo);
        } else { 
          alert('jgjhg');
        }
    }
});
}

now ajax.php:-

if($_REQUEST['action'] == 'do_this') {
echo 'ok';
}

Upvotes: 4

Related Questions