Javascript assign variable from function

I have a js function , after doing some business logic, the javascript function should return some result to another variable.Sample code below

var response="";
function doSomething() {  
    $.ajax({
        url:'action.php',
        type: "POST",
        data: dataString,
        success: function (txtBack) { 
            if(txtBack==1) {
                status=1;
            }
    });
    return status;     
}

Here i want to use like

response=doSomething();

I want to assign a return value "status" "var response".But the result is 'undefined'.

GEOCHET

20.8k15 gold badges73 silver badges98 bronze badges

asked Oct 15, 2010 at 10:27

6

Or just...

var response = (function() {
    var a;
    // calculate a
    return a;
})();  

In this case, the response variable receives the return value of the function. The function executes immediately.

You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.

answered Oct 15, 2010 at 10:34

Šime VidasŠime Vidas

176k60 gold badges279 silver badges375 bronze badges

4

AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status is undefined when it is returned.

Effectively, your code works as follows:

function doSomething(someargums) {
     return status;
}

var response = doSomething();

And then some time later, your AJAX request is completing; but it's already too late

You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.

Where you previously may have had

var response = doSomething();

alert(response);

You should do:

function doSomething() {  
    $.ajax({
           url:'action.php',
           type: "POST",
           data: dataString,
           success: function (txtBack) { 
            alert(txtBack);
           })
    }); 
};

Alexis Tyler

1,1716 gold badges30 silver badges47 bronze badges

answered Oct 15, 2010 at 11:17

MattMatt

73.1k26 gold badges149 silver badges179 bronze badges

You could simply return a value from the function:

var response = 0;

function doSomething() {
    // some code
    return 10;
}
response = doSomething();

answered Oct 15, 2010 at 10:28

Darin DimitrovDarin Dimitrov

1.0m266 gold badges3249 silver badges2911 bronze badges

1

The result is undefined since $.ajax runs an asynchronous operation. Meaning that return status gets executed before the $.ajax operation finishes with the request.

You may use Promise to have a syntax which feels synchronous.

function doSomething() { 
    return new Promise((resolve, reject) => {
        $.ajax({
            url:'action.php',
            type: "POST",
            data: dataString,
            success: function (txtBack) { 
                if(txtBack==1) {
                    resolve(1);
                } else {
                    resolve(0);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                reject(textStatus);
            }
        });
    });
}

You can call the promise like this

doSomething.then(function (result) {
    console.log(result);
}).catch(function (error) {
    console.error(error);
});

or this

(async () => {
    try {
        let result = await doSomething();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
})();

answered Aug 15, 2019 at 12:19

AleyAley

8,3607 gold badges41 silver badges54 bronze badges

The only way to retrieve the correct value in your context is to run $.ajax() function synchronously (what actually contradicts to main AJAX idea). There is the special configuration attribute async you should set to false. In that case the main scope which actually contains $.ajax() function call is paused until the synchronous function is done, so, the return is called only after $.ajax().

function doSomething() {
    var status = 0;
    $.ajax({
        url: 'action.php',
        type: 'POST',
        data: dataString,
        async: false,
        success: function (txtBack) {
            if (txtBack == 1)
                status = 1;
        }
    });

    return status;
}

var response = doSomething();

answered Mar 20, 2017 at 15:44

impulsgrawimpulsgraw

8372 gold badges11 silver badges34 bronze badges

Can you assign a variable to a function JavaScript?

You can work with functions as if they were objects. For example, you can assign functions to variables, to array elements, and to other objects. They can also be passed around as arguments to other functions or be returned from those functions. The only difference with objects is that functions can be called.

How do you call a function variable in JavaScript?

The JavaScript call() Method The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

Can you return a variable from a function JavaScript?

JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned.

Can you assign a variable to a function?

In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability. Simply assign a function to the desired variable but without () i.e. just with the name of the function.