Grizzly
Grizzly

Reputation: 5953

Ajax success not setting value of variable

I have a simple ajax call on one of my views.

var countAnchors;

$.ajax({
    url: countUrl,
    method: "GET",
    data: @Model.InitialTrainingId,
    success: function (result) {
        console.log("result: ",result);
        countAnchors = result;
    },
    error: function (jqXHR) {
        console.log(jqXHR);
        alert("There was a problem");
    }
});

console.log("countAnchors: ",countAnchors);

When I run this, in the console I am seeing:

enter image description here

Why isn't countAnchors being assigned the value in the success function?

Upvotes: 1

Views: 2808

Answers (3)

Adrian
Adrian

Reputation: 91

Your log entries are giving you a hint.

Unless you specify otherwise, ajax calls will run asynchronously.

In this case, you are seeing in the log that your logging of the value of countAnchors happens before the ajax call has completed. Just because it was written earlier in the script block doesn't mean (in this case) that it's finished before the next part of the script block is executed.

I bet this will give you a value, and will return the two lines to the console log in the expected order:

var countAnchors;

$.ajax({
    url: countUrl,
    method: "GET",
    data: @Model.InitialTrainingId,
    success: function (result) {
        console.log("result: ",result);
        countAnchors = result;
        console.log("countAnchors: ",countAnchors);
        doSomething();
    },
    error: function (jqXHR) {
        console.log(jqXHR);
        alert("There was a problem");
    }
});

function doSomething()
{
    alert('countAnchors: ' + countAnchors);
}

EDIT: If you need to do something with the value of countAnchors, create a new javascript function and call it from the success function after countAnchors is set.

Upvotes: 1

Swati
Swati

Reputation: 28522

You can make a function ,so whenever response comes you can assign value to your variable like below:

var countAnchors=null;

  function result(r){
    countAnchors= r;//assigning value return
   console.log("countAnchors: ",countAnchors);
  }

    $.ajax({  
        type: "POST",  
        url: "readString.php",  
        data: { 'fn': filename },      
        success: function(response){
            result(response); //calling function
        },
       error: function (jqXHR) {
       console.log(jqXHR);
       alert("There was a problem");
      }
    }); 

Upvotes: 2

feihoa
feihoa

Reputation: 517

Because

console.log("countAnchors: ",countAnchors);

run before success function and at this time 'countAnchors' is still undefined

Upvotes: 0

Related Questions