I have the following JavaScript code where I’m trying to get some data from an action in a WebAPI project. The problem I’m having is that when I go to use the dataset variable, I get an error saying that dataset is undefined. Also, I would expect my alert No. 1 to fire first, but the alert No. 2 fires first, with the dataset as undefined, then the alert No. 2 fires, and it then contains my data. What am I doing wrong here?
<script type="text/javascript">
$().ready(function() {
var dataset;
$.get("http://localhost:9619/api/values", function(data) {
dataset = data;
alert("No. 1 " + dataset);
});
alert("No. 2 " + dataset);
});
</script>
$.get()is asynchronous. So the execution of the callback is delayed until the request has finished.The execution order in your case is something like this:
You should add all code reliant on the
$.get()request to the respective callback. That way you make sure the request has succeed and your variables are set.Another less preferable solution would be to use
$.ajax()and set itsasyncparameter to false. But in that case, the execution of all JavaScript code waits until your request finishes and your page freezes in the mean time.