Reputation: 1191
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?
Upvotes: 1
Views: 62
Reputation: 1
You are missing $
before immediately invoked function expression, if you are expecting jQuery()
alias for .ready()
to be called when document
has loaded DOM
and #airline-select
is defined in document
at HTML.
You can pass url
to makeRequest()
within change
event handler by defining an expected parameter at the function declaration.
$(function() {
var httpRequst, url;
$("#airline-select").change(function () {
url = "{% url 'airline_year_financial_data' %}";
makeRequest(url)
});
// create and send an XHR request
function makeRequest(url) { // include `url` parameter at function
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url)
httpRequest.send()
}
//
})
Upvotes: 2