1

Context

I have a function that is called within an AJAX call that returns a number. I set this number to a variable and want to access the number outside of the .done() method:

$.ajax({
    url: 'urlhere.php',
    type: 'GET',
    data: {text: text},
    success: function(data) {

        var getNumber = countNumber();
        getNumber.done(function(data) {

            var number = data;

        });

        let newContent = 
        "The number is "+
        number;

    }
});

But I get this error, stating that the variable is not defined:

Uncaught ReferenceError: number is not defined

Question

How do I access variables within the .done() method in jQuery in an AJAX call?

Things I Have Tried

I have already tried defining the variable before the function call and then changing it in the done() method, like so:

var number; //initialize variable

$.ajax({
    url: 'urlhere.php',
    type: 'GET',
    data: {text: text},
    success: function(data) {

        var getNumber = countNumber();
        getNumber.done(function(data) {

            number = data;

        });

        let newContent = 
        "The number is "+
        number; //console.log's "undefined"

    }
});

This only makes the variable equal to undefined, so I don't think anything inside the done() method is able to change existing variables. Any ideas? Let me know if there is any confusion. Thanks.

Carson D
  • 81
  • 13
  • Try putting your ajax call in a function, and just before calling the function, make sure the "number" variable is declared and defined with desired value. – Pranav Rustagi Aug 14 '20 at 07:25

2 Answers2

1

It seems getNumber.done() is asyncronous. Which means it takes a while to update the the value of number;

You may do this:

$.ajax({
    url: 'urlhere.php',
    type: 'GET',
    data: {text: text},
    success: function(data) {

        var getNumber = countNumber();
        getNumber.done(function(data) {

            number = data;
            let newContent = "The number is "+ number; //console.log's "undefined"
        });

    }
});
Edson Magombe
  • 313
  • 2
  • 14
1

Your problem is that the code is asynchronous so the number variable won't be assigned just after you can the done() function.

var getNumber = countNumber();
getNumber.done(function(data) {

    number = data;

});

// number won't exist here.
let newContent =   "The number is "+ number; //console.log's "undefined"

What you can do:

  • Use a promise and use resolve on the done() callback. You will need to await after it.
  • Call a function from .done() callback and keep your process from there

Something like this:

    var getNumber = countNumber();
    getNumber.done(function(data) {

        number = data;
        // Your code should flow from here.
        yourDoneFunction();
    });
César Ferreira
  • 681
  • 1
  • 5
  • 12