Php function returns always zero

I’ve a form with a password field

<form id="form-login" class="row-fluid" novalidate="novalidate" method="post" action="#">
<input class="span12" type="password" name="password" pattern="[0-9 ]{5,15}" />
</form>

when submit the form I do an Ajax call:

Read More
...
var data = $('form').serialize();

$.ajax({

    url: "/wp-admin/admin-ajax.php", // wordpress
    type: "POST",
    data: data + '&action=login_check',
    cache: false,

    success: function (html) {           
        $('.loading').hide();

        if ( html == 0 ) {
            $('.undone').fadeIn('slow');
        } else if ( html == 1 ) {
            $('.done').fadeIn('slow');                  
        }
    }
}); 

return false;
...

that check password using this function in functions.php (WordPress):

function login_check(){

        $pw = 'hello';

        if( md5($pw) == md5($_POST['password']) ){

            $_SESSION['key'] = 1;
            return 1;

        } else {

            return 0;

        }

    die();

}

add_action('wp_ajax_login_check', 'login_check');
add_action('wp_ajax_nopriv_login_check', 'login_check');

and I want that the above function returns 0 or 1 to the success function in the ajax call. But it returns always 0, also when insert the correct password. Where am i wrong?

var_dump($_POST);

array(3) {
  ["password"]=>
  string(5) "hello"
  ["s"]=>
  string(0) ""
  ["action"]=>
  string(11) "login_check"
}

Related posts

Leave a Reply

1 comment

  1. You check for a Number in your javascript ajax callback handler. But the html param will be acutally a String. Change the callback to:

    if ( html == '0' ) {
        $('.undone').fadeIn('slow');
    } else if ( html == '1' ) {
        $('.done').fadeIn('slow');                  
    }
    

    What happens? You formally, (before edition the question) returned nothing '' on success and '0' an error. But because of the loose typing system of javascript both evaluated to ==0. Check this javascript code:

    ""==0;  // true
    "0"==0; // true
    

    Also change the return statements in PHP into echo statements. Note that the return statement actually outputs nothing:

    if( md5($pw) == md5($_POST['password']) ){
        $_SESSION['key'] = 1;
        echo '1';
    } else {
        echo '0';
    }