Jump to content

Help Setting Variable


slj90

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.