I'm trying to declare a variable inside function and wants to make it available outside that function. I have gone through several Stackoverflow answers but still cant figure out.
script>
(function() {
var url
$("#airline-select").change(function () {
url = "{% url 'airline_year_financial_data' %}";
});
console.log(url)
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url)
httpRequest.send()
}
// Handle XHR Response
function responseMethod () {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
updateUISuccess(httpRequest.responseText)
} else {
// Do something
}
}
}
// Handle XHR Success
function updateUISuccess(responseText) {
var response = JSON.parse(responseText)
var a = $("#airline-select").val();
var width = 500;
var height = 300;
var padding = 20;
d3.select("body")
.append("svg")
.attr("class", "waterfall-container")
.attr("width", width)
.attr("height", height)
.attr("style", "outline: thin solid")
d3.select("svg")
.selectAll("rect")
.data(response)
.enter()
.append("rect")
.attr("x-axis", 200)
.attr("y-axis", 300)
.attr("width", 20)
.attr("height", 200)
.attr("fill", "blue")
}
})();
</script>
It logs 'undefined' at the console which means the value of url inside the function is getting updated or not available outside the function. How can I do that?
undefinedbecause that element, which has an event listener (on change), has not yet been changed. In that case, because you declaredvar url(which is sayingvar url = undefined, loggingurlshould correctly yieldundefined