Alvin
Alvin

Reputation: 657

problem in variables in jquery

I don't understand why I'm not getting the message as "username already exits" if type the username which is already in database.

If the username in a server, then it is returning the value as "1" otherwise empty, and despite of successfully getting the value from the server based on username is present or not, and assigning the value to variable "x", I'm unable to get message when I pass already exist username. May I know?

$(document).ready(pageInit);
function pageInit() {
$('#1').bind('blur',go);
}
function go() {
 var value = $('#1').val();
 var x = 0;
 $.post('just.do',{username:value},function(data){
    x = data;

   }
);

 if(x) {
      $('#para').show();
      $('#para').html("Username already exits");
         return false;
  }
 else {
    $('#para').hide();
       return true;
  } 
};

EDIT: This is what I'm doing in post request in servlets:

String user1 = request.getParameter("username");  
   if(user != null) {
         String query = "Select * from users where user_name="+"\""+user+"\"";
         b = db.doExecuteQuery(stmt,query);
         if(b) {
          out.write("1");
         }

}

Upvotes: 1

Views: 63

Answers (2)

Nick Craver
Nick Craver

Reputation: 630379

You need to rearrange your go() function a bit, like this:

function go() {
  $.post('just.do',{username: $('#1').val()},function(data){
    if(data) {
      $('#para').show();
      $('#para').html("Username already exits");
      return false;
    } else {
      $('#para').hide();
      return true;
    } 
  });
}

$.post() is an asynchronous operation, so that x=data was happening after your if(x) ran...you need to rearrange a bit so that it happens after the response comes back, e.g. running or triggered from inside the callback like I have above.

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129792

Your code if(x) ... executes before the http request finishes, and as a result, x will never be set when that part of the code is reached.

You want to use callbacks:

$.post('just.do',{username:value},function(data) {
   receivedResult(data);
});

...

function receivedResult(x) {
    if(x) {
     ...
    } else {
     ... 
    }
}

Upvotes: 4

Related Questions