Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run AJAX every x seconds with different data each time

I have the below code whichs executes every 5 seconds. However i would like to return different data each time.

For example:

First interval = top level data (level.php)
Second interval = top skill data (skill.php)
Third interval = top magic data (magic.php)

And once the third interval is done… return to level.php to start the sequence again

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone tell me how would i modify the code to achieve what i want?

<script>
    var text = "";
    var toplevel = function() {
        $.ajax({
            type : 'GET',
            url : '/pages/level.php',
            success : function(data){
            text = data;
            $("#tops").fadeOut( "normal", function() {
                $('#tops').html(data);
                $("#tops").fadeIn( "normal", function() {});
                });
            },
        });
    };

    $(document).ready(function(){
        setInterval(toplevel, 5000);
        toplevel();
    });
</script>

>Solution :

You could have an array of URLs, always send the request to the first one, and rotate the array order on success:

function toplevel(urls) {
    return function () {
        $.get(urls[0]).done(function (data) {
            urls.push(urls.shift());
            $("#tops").fadeOut("normal", function () {
                $('#tops').html(data).fadeIn( "normal");
            });
        });
    }
};

$(function () {
    var switcher = toplevel(['/pages/level.php', '/pages/skill.php', '/pages/magic.php']);
    setInterval(switcher, 5000);
    switcher();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading