How to Access a Variable Outside of an AJAX Function with jQuery



JQuery


In this article, we show how to access a variable outside of an AJAX function with jQuery.

So if you common AJAX functions such as get() functions, you normally have variables declared in these functions. But you may want to use these variables outside of this given function. How can you access the value of a variable outside of an AJAX function?

So let's say we have the following code shown below.





So in the following code above, we have AJAX code.

We first do a POST request, followed by a GET request, which is fairly common to AJAX code. You first make a POST and then you retrieve the data.

We have a get function, which has one parameter, which is the variable, data.

Of course, we can access this data variable within this get() function.

If we need to access this data variable outside of this get() function, we cannot do it directly without adding some extra code. If we attempt to reference this data variable outside the get() function without using a done() function, the data variable will be undefined.

In order to access the data outside of this get() function, we need to use the done() function.

We have to make sure that the get() function is executed and completely finished before we can attempt to access any variable of the get() function. Otherwise, the variable will be undefined. And we do this through the done() function. The done() function executes only after the function attached to it is finished. This ensures that the variable will have a defined value.

In the following code below, we can access the variable now outside of the get() function.





So using the done() function and passing in the variable we want as a parameter, we can now access the variable in this function.

This is how it must work.

You cannot access a variable outside of the function unless it is sure that the function is done executing. This is why you must use the done() function to make sure that the function is done executing and the variable it contains is defined.

And this is how to access a variable outside of an AJAX function with jQuery.


Related Resources

How to Hide an HTML Element with jQuery

How to Show an HTML Element with jQuery

How to Create a Comment System in Which Only One Reply Comment Box Can Be Open At Once with jQuery

How to Upload a File with the Click of an Image with jQuery



HTML Comment Box is loading comments...