I am encountering a strange Javascript behavior:
index.html
<div id="content">
<button type="button" onclick="goDownload()">Click</button>
</div>
hello.html
<div id="myId">
</div>
<script type="text/javascript">
$(function() {
doStuff();
});
</script>
file.js
function goDownload() {
$.ajax({
url: "hello.html",
cache: false,
success: function (response) {
$("#content").append(response);
}
});
}
function doStuff() {
//If I wait a little bit (e.g alert/timer), the below works
//otherwise it does not
$("#myId").html("Hello from doStuff()");
}
I know the ajax call is a async request, but I cannot see at what point this is becoming an issue. (I know I can do my doStuff() in success callback, but this is not the case for me). Any ideas?
The result of an
$.ajaxcall is a Deferred object ( http://api.jquery.com/category/deferred-object/ ), so you can take advantage of its methods to detect when it’s done: