-2

I have this code and I want to specify if the validateUser function is true or false. How can I do it since in the code there is already a function in the .post()?

Here is the code

function validateUser() {

    var user = $("#username").val();

    $.post('usercheck.php', $("#form").serialize(), function (data) {
        var usercheck = data;

        if (usercheck != "") {
            $("#div").html("Username already exists");
            return false;
        } else {
            $("#div").html("ok");
            return true;
        }

    });
}
Allan Kimmer Jensen
  • 4,333
  • 2
  • 31
  • 53
valemax
  • 41
  • 7
  • 1
    http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Deepak Ingole Feb 10 '14 at 11:15
  • You can make this ajax call synchronized. and declare a variable result in function validateUser scope and inside the post call you assign value true or false and then add return statement after post call return result; – Ravi Kumar Feb 10 '14 at 11:16

2 Answers2

1

The problem is, that the $.post is async. So you'd need to pass a callback to your validateUser function.

function validateUser(callback) {
  var user = $("#username").val();
  $.post('usercheck.php', $("#form").serialize(), function(data) {
    var usercheck = data;
    if(usercheck != "") {
      $("#div").html("Username already exists");
      callback(false);
    }
    else {
      $("#div").html("ok");
      callback(true);
    }
});

validateUser(function(valid) {
    if (valid) {
        alert('The user is valid');
    }
    else {
        alert('The user is not valid');
    }
});
plu
  • 1,321
  • 10
  • 14
0

You can't return true of false, since jQuery.post run asynchronously. A work-around would be to force post to run synchronously, but I strongly recommend you to do NOT do it that way.

Anthony Garcia-Labiad
  • 3,531
  • 1
  • 26
  • 30