Reputation: 6763
Data lines do not show on graph when alert("inside function: " +data);
is commented out below, but when its uncommented and user dismisses the alert the graph is populated with datasets.
Could the data not be fully loaded by the time $.plot
is called?
[01:05:21.158] TypeError: myfile is undefined @ http://localhost:8080/App/js/App.js:7
Script ..
$(function() {
var plotarea = $("#placeholder"),
myfile = Script_JSON.getData("myfile"),
anotherfile = Script_JSON.getData("anotherfile");
$.plot(plotarea, [myfile.data, anotherfile.data]);
});
var Script_JSON = {
getData: function(component) {
var data;
$.getJSON("data/" + component + ".json", function(json) {
data=json;
});
//alert("inside function: " +data);
return data;
}
};
Upvotes: 0
Views: 191
Reputation: 6763
Used a Java Servlet to read the json data from files and send to javascript with AJAX ..
var App_AJAX = {
getData: function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", "Servlet, true);
xmlhttp.send(null);
function callback() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#body").append('<div id="content"><div class="demo-container"><div id="placeholder" class="demo-placeholder"></div></div></div>');
var datasets = JSON.parse(xmlhttp.responseText);
} else {
// have not recieved data yet
}
}
}
};
Upvotes: 0
Reputation: 38219
There are a ton of duplicate questions for this, but none with a very direct answer.
AJAX requests, e.g. getJSON, are asynchronous. When you make the call, it returns immediately, while the success function that you provided isn't called until some time later. This can be anywhere from a few milliseconds to several seconds, depending on the request.
So calling plot on the very next line, expecting the results to have arrived already, is not going to work. You need to plot inside your success callback.
In your case, where you have two separate loads, you will need to check in each one whether the result of the other one has already arrived. If so, you can plot; otherwise you need to return and let the other callback take care of it.
Upvotes: 3