Reputation: 988
I have a link like this:
<a href="page.html" onclick="loadAjax();">link</a>
page.html is verry long to load (due to a long process server-side).
The loadAjax function is like this:
function loadAjax() {
setTimeout(function() {
$.getJSON('otherPage.json', function(data) {
$.each(data, function(key, val) {
//do something
});
});
}, 2000);
}
But when I click the link, page.html is loading and Ajax query stops. In Chrome's developper tool I see "canceled" next to otherPage.json.
So I have to load otherPage.json after loading of page.html starts because it get data modified by page.html's process.
Upvotes: 2
Views: 1743
Reputation: 988
I changed $.getJSON for $.ajax to add "async: false" and it solved my problem.
Upvotes: 2
Reputation: 5647
well if you click a link, and refer to a different page, all running requests for the current page are cancelled...
this is the expected and wanted behaviour (to prevent unnecessary loading).
if you need a simultaneous loading of two separate pages, you need 2 ajax requests. this means:
$('#htmlpagelink').click(function(){
loadAjax(page.html);
loadAjax(otherPage.json);
});
function loadAjax(url){
/* ... code ... */
}
Careful, this does not change the current page, so if your user clicks a different link you gotta do it all over again.
instead you could speed up the first showing of results, by having your server return a comparably small and thus fast html-page, that directly starts loading data from the server with exactly this construct. something like this should do the trick:
<html>
<head>
<title>Page Title - loading...</title>
<script type="text/javascript">
$(document).load(loadContent());
function loadContent(){
//see upper code-block
}
</script>
</head>
<body>
<img src="/loading.gif" alt="loading..." />
</body>
</html>
Upvotes: 1
Reputation: 2432
How it will work; on onlick your href attribute will take precedence and ajax call will stop.
Load the .html page after ajax call finished.
<a href="#" onclick="loadAjax();">link</a>
and in loadAjax() function, assign page dynamically to href attribute.
function loadAjax() {
setTimeout(function() {
$.getJSON('otherPage.json', function(data) {
$.each(data, function(key, val) {
//do something
});
});
}, 2000);
this.href="Page.html"
}
Use ref variable to this ( always a good practice)
Upvotes: 1