I had an issue which I, after several hours of searching, solved when I stumbled upon the fact that one can set the async-option for an ajax-call to false. My code now works exactly as I expect to, but I wonder if my solution is good or if it can be solved in a better way. If my solution is bad, why do you think so? Async vs sync, what is best? Should one always strive to use async-calls as much as possible?
var pageIndex = 0;
(function () {
GetData();
$(window).scroll(function () {
if ($(window).scrollTop() ==
$(document).height() - $(window).height()) {
GetData();
}
});
})();
$.ajax({
type: 'GET',
url: '/Blog/GetPostsByBlogId',
data: { "id": @Model.First().ReqBlog.Id, "pageindex": pageIndex },
dataType: 'json',
success: function (response) {
DisplayData(response);
},
beforeSend: function () {
$("#progress").show();
},
complete: function () {
$("#progress").hide();
},
error: function (response) {
alert("Error while retrieving data!");
}
});
In the success I call the following function:
function DisplayData(response)
{
if (response != null) {
$.each(response, function (i, post) {
$.ajax({
async: false,
url: "/Blog/GetPostPartialView",
data: post,
type: "POST",
success: function (response) {
$("#posts-container").append(response);
}
});
});
pageIndex++;
}
}
Without the "async: false" the data is displayed in a random order for every refresh. With the "async: false" the data displays in the correct order, every time.
Edit:
I used the following solution to avoid using async: false.
My DisplayData-function now looks like this:
function DisplayData(response)
{
if (response != null) {
$.each(response, function (i, post) {
$('#posts-container').append($('<div>').load("/Blog/GetPostPartialView", { Id: post.Id, Title: post.Title, Body: post.Body, Created: post.Created, Updated: post.Updated, Views: post.Views, Blog: post.Blog, Tags: post.Tags, Comments: post.Comments, Author: post.Author }));
});
pageIndex++;
}
}