tags:

views:

48

answers:

3

Hi,

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' Please help me to fix this.

Thanks in advance.

+2  A: 

You could simply return a value from the function:

var response = 0;

function doSomething() {
    // some code
    return 10;
}
response = doSomething();
Darin Dimitrov
Its working... but i have ajax call inside, in thats time the result is 'undefined'. Any idea? Please look at the modified sample code.
Ra
A: 

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.

Šime Vidas
+1  A: 

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