2

So this is my code for some ajax that I'm doing.

function check_password(){

  var username = $("#username").val();
  if(username.length > 0){
    var bool = -1;
    $('#Loading2').show();
    $.post("check_login.php", {
      username: $('#username').val(),
      password: $('#password').val(),
    },
    function(response) {
      $('#Info2').fadeOut(500);
      $('#Loading2').hide();
      bool = response.indexOf('success');
      setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
      $('#password').after(bool);
      return response.indexOf('success');  
    });

  }
}

function finishAjax(id, response){

  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn(750);
} 

and here I'm trying to handle the return value from the check password function.

jQuery(function() {
  $("#submitl").click(function(){
    $(".error").hide();
    var hasError = false;
    var passwordVal = $("#password").val();
    var username = $("#username").val();

    if (username == '') {
      $("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
      hasError = true;
    } else if (passwordVal == '') {
      $("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
      hasError = true;
    } else if (check_password() != 73) {
      hasError = true;
      $("#password").after(check_password());
    }
    if (hasError == true) {
      return false;
    }
  });
});

For some reason the if statement is returning true even when the index(return value) is 73. I test this by using jquery within the if statement to print out the value of the returning function and it prints out 73. I have a feeling my error is caused because of dynamically typed variables in javascript.

Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
Brian Hauger
  • 490
  • 1
  • 4
  • 22
  • It is asynchronous not synchronous. Your function will not wait for the result so will always be TRUE. – Tim B James Apr 15 '13 at 22:22
  • 1
    Possible duplicate of: dozens of questions per month ;-) – jahroy Apr 15 '13 at 22:25
  • passing a string to `setTimeout`?... please don't do that – Elias Van Ootegem Apr 15 '13 at 22:27
  • Voting to close AND upvoting since I suspect others new to Javascript might also come to the conclusion "The if statement has failed me" and land here when googling - I'm pretty sure closed questions get auto-deleted if they have a low score (3 or below?) which would ruin the future googletunities. – Chris Moschini Apr 15 '13 at 22:55
  • If you want to avoid running into problems with implicit casts you might want to stick to `===` instead of `==`. – Michael W Apr 15 '13 at 23:50

3 Answers3

1

Typical asynchronous behavior issue of AJAX calls. You return response.indexOf('success'); from your AJAX callback, but since it is an asynchronous callback, there is nothing to return to. The rest of you check_password function has long finished when the callback is being called.

To fix this you need to completely restructure your code. In your click handler, you first need to call your post() function and then in the callback you need to go through your if/else if blocks.

Steve
  • 8,609
  • 6
  • 40
  • 54
0

Your function ´checkpassword()´ doesn't actually return a value. It launches a request to a PHP-file and immediately returns (without a value).

You do specify a callback for when the call returns, but that never gets back to your original function.

You could do something like this:

function check_password(callback){

  var username = $("#username").val();
  if(username.length > 0){
    var bool = -1;
    $('#Loading2').show();
    $.post("check_login.php", {
      username: $('#username').val(),
      password: $('#password').val(),
    }, function(response){
      $('#Info2').fadeOut(500);
       $('#Loading2').hide();
      bool = response.indexOf('success');
      setTimeout("finishAjax('Info2', '"+escape(response)+"')", 450);
      $('#password').after(bool);
      callback(response.indexOf('success'));
    });

  }
}
function finishAjax(id, response){

  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn(750);
} 


jQuery(function(){
        $("#submitl").click(function(){
        $(".error").hide();
        var hasError = false;
        var passwordVal = $("#password").val();
        var username = $("#username").val();
    if (username == '') {
            $("#username").after('<span style="color:red" class="error"><p></p>Please enter a username.</span>');
            hasError = true;
        } 
    else if (passwordVal == '') {
            $("#password").after('<span style="color:red" class="error"><p></p>Please enter a password.</span>');
            hasError = true;
        } 
    else (
        check_password(function(returnValue) {
            if (returnValue  != 73) {
                hasError = true;
                $("#password").after(check_password());            
            }
         })){

        }
        if(hasError == true) {return false;}
    });
});

Of course, this code just shows you how to get the value inside the other function, but you still need to handle the fact that you're other function doesn't return immediately and that for example the value of HasError is not set immediately.

Kenneth
  • 28,294
  • 6
  • 61
  • 84
0

Your problem is that you return from within a inner function, which will never ever work in JavaScript. Pass a callback:

function check_password(callback) {
    // ...
    callback(response.indexOf('success'));
}
// ...
check_password(function(result) {
    if(result != 73) {
        // ...
    }
})

Just search for JavaScript AJAX and you will find a lot of sites to study. Here is one of them: http://www.html5rocks.com/en/tutorials/async/deferred/

jgillich
  • 71,459
  • 6
  • 57
  • 85