1

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");
         }

}

1
  • you should post your server side code too Commented May 25, 2010 at 12:25

2 Answers 2

4

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 {
     ... 
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.