0

When I use this code then multiple time ajax call 4-5 time load same data in output. Please help me to solve this. Please see the flowing code.

<script>
    $(document).ready(function () {
        $(window).scroll(function () {
            if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
                sendData();
            }
        });

        function sendData() {
            var offset_val = $('#offset_val').val();
            $.ajax({
                url: '',
                type: 'POST',
                data: {offset_val: offset_val},
                dataType: "json",
                success: function (response) {
                    if (response.status) {
                        $('#load_data').append(response.all_data);
                        $('#offset_val').val(response.offsets);
                        setTimeout(function () {
                            //$('.animation_image').hide();
                        }, 600);
                    } else {
                        $('#no-data-found').html(response.all_data);
                       // $('.animation_image').hide();
                    }
                }
            });
        }

    });

</script>
Pervez
  • 516
  • 6
  • 10
  • Have you try deleting the browser cache after each call? If deleting the browser cache solve your problem, then we need something like timestamp in your request to invalidate the cache – samAlvin Jun 15 '17 at 07:10
  • What will make the data change? Is there a different output for every offset? – showdev Jun 15 '17 at 21:16

1 Answers1

1

That's not the ajax issue, check the following line:

$(window).scroll(function () {
    if ($(document).height() - 50 <= $(window).scrollTop() + $(window).height()) {
        sendData();
    }
});

The above code executes for each single scroll moment when condition return true. That's why it is initiating multiple request for a single scroll.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
  • @Pervez If this is the problem you're experiencing, you might consider ["throttling" or "debouncing"](https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function) your function, so that scroll events don't continuously execute it. – showdev Jun 15 '17 at 21:18