variable scope issue in jQuery post method -
this question has answer here:
- how return response asynchronous call? 25 answers
i trying information database , make chart them. unfortunately, variables use store values losing data outside of post
. completed
, ongoing
assigned inside post
methods, each other's post methods, not outside of it. when data2
executes, variables become empty again. how can fix issue?
var completed; var ongoing; $.post( "/api/educationcompletionrates?status=1&startdate=20150701&enddate=20150705", { data: {} }, function (data) { completed = data; } ); $.post( "/api/educationcompletionrates?status=2&startdate=20150701&enddate=20150705", { data: {} }, function (data) { ongoing = data; } ); var data2 = [ { value: completed, color: "#46bfbd", highlight: "#5ad3d1", label: "completed" }, { value: 700, //ongoing, color: "#fdb45c", highlight: "#ffc870", label: "ongoing" } ]
this due ajax requests being asynchronous, not due variable scope. full explanation of issue, see answers in this question. solve problem in specific case, can use $.when
calback create data2
object after both ajax calls have completed. try this:
var completed; var ongoing; var requests = []; requests.push($.post( "/api/educationcompletionrates?status=1&startdate=20150701&enddate=20150705", { data: {} }, function (data) { completed = data; } )); requests.push($.post( "/api/educationcompletionrates?status=2&startdate=20150701&enddate=20150705", { data: {} }, function (data) { ongoing = data; } )); $.when.apply(this, requests).done(function() { var data2 = [{ value: completed, color: "#46bfbd", highlight: "#5ad3d1", label: "completed" }, { value: ongoing, color: "#fdb45c", highlight: "#ffc870", label: "ongoing" }]; // add further logic relies on data2 here... });
note approach quicker nesting ajax calls run in parallel, rather in chain. therefore user waiting long slowest request.
Comments
Post a Comment