mardi 17 février 2015

Check if function returns any data in Ajax and WebMethod


I've developed the following system that returns endless scroll data on an aspx page. It works perfectly well. However I have a small problem checking whether the database has reached the end row and no data is returned.


With the following code the javascript function keeps on calling the webmethod everytime the page scroll hits the bottom although there is no data to return. How can I check there is no data to avoid those meaningless function calls?



$(document).ready(function () {
var offset = 0;
var fetch = 30;

function Load() {
$.ajax({
type: "POST",
url: "UserControls/uc_functions.aspx/LoadLatest",
data: "{offset :" + offset + ", fetch: " + fetch + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") { $('.latest').append(data.d); }
else {alert("no data"); completed = true; } //I never get this alert even when there is no data returned from the database
}
})
};

$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 10) {
Load(offset, fetch);
offset = offset + fetch;
}
});
});


[WebMethod]
public static string LoadLatest(int offset, int fetch)
{
var LoadSql = db.Query("Exec dbo.SD_unionServices @0, @1", offset, fetch);");
foreach (var item in LoadSql)
{
Load_sb.Append(item.title + "<br />");
}

if(LoadSql.Count() > 0)
return Load_sb.ToString();
else
return string.Empty;
}


UPDATE To check whether the data is empty or not I used data.d instead of data



if (data.d != "") { $('.latest').append(data.d); }


Instead of



if (data != "") { $('.latest').append(data.d); }




Aucun commentaire:

Enregistrer un commentaire