Variable assign don't work within function (Ajax, JS)

Go To StackoverFlow.com

1

I can't understend why variable "s_return" dont work

$('.codeinput').change(function() {
var s_return="";        
var to_check=this.value ;

        $.ajax({
  type: "POST",
  url: "check.php",
  data: "code="+to_check}).done(function( msg ) {
    s_return=msg; // msg - variable work fine

});

// here variable "s_return" is unset
this.value=s_return;
});

I will appreciate any help.

2012-04-04 22:40
by Alexandr Sopkov


2

s_return=msg;

is inside an async function. It will be set, when the server responses.

this.value=s_return;

runs right after the request is fired. therefore s_return isn't set, yet.

You will need to do it like this:

$('.codeinput').change(function() {
    var that = this;
    var s_return="";        
    var to_check=this.value ;

    $.ajax({

      type: "POST",
      url: "check.php",
      data: "code="+to_check

    }).done(function( msg ) {
        that.value=msg;
    });

});
2012-04-04 22:42
by binarious


1

The AJAX call runs asynchronously. If you step through it, you'll see that this.value=s_return; executes before s_return=msg; does, so s_return is still empty when you do the this.value=s_return; assignment.

2012-04-04 22:42
by Tuan
Ads