Gateway Gateway -4 years ago 145
Ajax Question

Ajax to fire on page load

I'm hoping someone can find what my issue is. my script only fires when scrolled down... I need that functionality. What it doesn't do is fire on page load too which I need it to do initially. So it loads the content first, then I can scroll down the page for more new content.

I tried putting the ajax inside a function with the function name outside and it still didn't fire.

$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
flag = true;
first = $('#first').val();
limit = $('#limit').val();
no_data = true;
if (flag && no_data) {
flag = false;
$('#loadmoreajaxloader').show();
$.ajax({
url: "commentedoncontent.php",
dataType: "json",
method: "POST",
cache: false,
data: {
start: first,
limit: limit
},
success: function(data) {
flag = true;
$('#loadmoreajaxloader').hide();
if (data.count > 0) {
first = parseInt($('#first').val());
limit = parseInt($('#limit').val());
$('#first').val(first + limit);
$.each(data.posts, function(i, response) {
//post content here
});
} else {
alert('No more data to show');
no_data = false;
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
flag = true;
no_data = false;
}
});
}
}
});
});

Answer Source

You need to separate it as a function, so you can call it on scroll AND on page load:

$(document).ready(function() {
    myFunction();
    $(window).scroll(function() {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 100) {
            myFunction();
        }
    });
});
function myFunction(){
    /* all the logic goes here */
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download