skip to Main Content

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.

2

Answers


  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"
            });
    
        }
    });
    
    Login or Signup to reply.
  2. 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();
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search