-2

When I am trying to return a value from jQuery function, it is not working.

Belwo is my function :

function reset() {       

   $.post("/class/function.php", { function:"random" },
        function(data) { return  data;   });

    }


 var new_val = reset();
 alert(new_val);
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • Its a kind of asynchronous call. If you want to happen things as you expected just set `async:false`. But its not a better approuch. – Rajaprabhu Aravindasamy May 20 '14 at 05:22
  • Sorry! I changed the function name.. – user3478403 May 20 '14 at 05:23
  • is there any possible ways to get the response from ajax.. – user3478403 May 20 '14 at 05:29
  • possible duplicate of [canonical asynchronicity topic](http://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-canonical) based on this [meta post](http://meta.stackoverflow.com/questions/254895/general-javascript-asynchronicity-reference-for-close-voting) – Abhitalks May 20 '14 at 05:37

1 Answers1

0

Due to the asynchronous nature of the Ajax call, the new_val that passed to the alert may not have the returned value from the Ajax call yet. Try this:

var new_val;
function reset() {       
    $.post("/class/function.php", { function:"random" },
        function(data) {
            new_val = data; 
            alert(new_val);  
        });
}
reset();
user3030212
  • 429
  • 3
  • 4