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.

2 Answers 2

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

});
Sign up to request clarification or add additional context in comments.

Comments

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.

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.