Enkhtuvshin Enkhtuvshin - 4 years ago 160
Javascript Question

call var in function to outside the function

I'm trying to call this variable outside the function but I get undefined as a result. I understand without var the variable could be called in global scope but i get undefined. I also tried setting the var outside the function and calling it but no success also. Here's my simplified code thank you :)

function function1() {

function successfunction(data) {
testvar = (data.name);
function failfunction(error) {


$( document ).ajaxStop(function() {}

to load the var after ajax load.

Answer Source

if you want global scope attach your variable to global object like window

function successfunction(data){
    window.testvar = "var";

By that you will be sure that it becomes global .

However, you should note that successfunction is a callback that will be running later on : it is running after timeout & only if the ajax call succeeded .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download