I've been looking around as to how to use a variable from one script on a page and use it in another script. I've found that you can set your variable to global (although this is not preferred, but I havn't found a better way).
I am using the Bootstrap framework.
On my page, I have an AJAX call in a function. I have declared the variable in front on the function so that it is a global variable. The value of the variable is set in the success function of the AJAX call.
In another script (inside a modal) I then use the variable to output as text. This works when I set the value of the variable outside the AJAX function, but it gives value='undefined' when the value is set in the AJAX success.
The modal in which the variable is used is only opened after the AJAX success function, but maybe the value is already read before the AJAX request, even when the modal is not shown? Is there a way to say that it only has to be loaded after the AJAX success function?
This is an abstract of my code for the AJAX function:
<script type="text/javascript">
var theVariable;
function() {
//AJAX Call
$.ajax({
//Abbreviated
success: function(data) {
theVariable = "test";
}
});
}
Here is the code I use in the modal to read the variable
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = theVariable;
</script>
So to recap, when I set the value of theVariable while declaring it (outside of the AJAX function), the value is displayed in the modal. However, when I try to set the value inside the AJAX success function this value is undefined.