Jump to content

Recommended Posts

 v=$("#txtusername");
  $.post('../actions/check.php',{user:v.val().toLowerCase()},function(d){
  if(d=='available'){
    $("#usernamemessage").html("<span style='color:green;'>Username is available</span>");
   }else  if(d=='not-available'){
  $( "#txtusername" ).effect( "shake" );
$('#txtusername').css('border', 'solid 2px blue');
 var iserror = '1'
 alert(iserror);
}
});

alert(iserror);

The first alert displays '1', however, the second displays 'undefined'. Why is this?

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/289075-help-setting-variable/
Share on other sites

Your problem may actually run deeper than scope. It really depends on what the rest of your code is. For example, even if you remove the var to put it in global scope, you also have a timing issue to deal with, because you are setting it within an ajax callback. So that 2nd alert() isn't really gonna work, even if you make the var global scope.

 

Consider this:

 

$.post(url,data,function(response) {
  iserror=true;
});

console.log(iserror);
That $.post is an AJAX call - asynchronous. That means when the request is made, the browser isn't going to wait around for it to send a response back before it moves on to the next code to execute. So even though you're setting iserror on a global level, it's not going to actually get set until the AJAX request receives a response. This could take 50ms or 10s, who knows. Meanwhile, the console.log has already executed.

 

So basically, you need to restructure your code to do something with iserror from within that callback, whether it be moving your code there or wrapping it in some function and calling it from within the callback.

 

$.post(url,data,function(response) {
  doSomething(iserror);
});

function doSomething(iserror) {
  console.log(iserror);
}
Point is, you need to restructure your code to have it execute when the callback is executed.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.