Call ajax with Jquery every X seconds

Asked

Viewed 1,040 times

1

I’m trying to make a call Ajax as soon as the page loads and one every 2 minutes.

The first and the second works, but there’s no third call and so on.

      <script type="text/javascript">

            function CarregarJSON() {
                $.ajax({
                    type: "get",
                    url: "/Extranet/Monitor/DadosServerIISJson",
                    success: function (data) {
                    CPUIIS = data.CPU_IIS;
                    $("#CPUIIS").html(CPUIIS);
    //remoção de código para facilitar visualização

                    }

                });

                $.ajax({
                    type: "get",
                    url: "/Extranet/Monitor/DadosServerSQLJson",
                    success: function (data) {
       //remoção de código para facilitar visualização
                    }

                });
            }



            $(document).ready(function () {
                CarregarJSON();

                timeout = setTimeout(function () {
                    CarregarJSON()
                }, 12000);

            })
        </script>

1 answer

2


Insert the new Ajax call into the callback. So ensure that the next request is sent only after the second ajax has arrived and also ensure that this is the right trigger, ie that whenever the ajax ends calls the function again.

function CarregarJSON() {
    var recebidas = 0;
    $.ajax({
        type: "get",
        url: "/Extranet/Monitor/DadosServerIISJson",
        success: function(data) {
            if (recebidas > 0) setTimeout(CarregarJSON, 120000);
            recebidas++;
            CPUIIS = data.CPU_IIS;
            $("#CPUIIS").html(CPUIIS);
            //remoção de código para facilitar visualização
        }
    });

    $.ajax({
        type: "get",
        url: "/Extranet/Monitor/DadosServerSQLJson",
        success: function(data) {
            if (recebidas > 0) setTimeout(CarregarJSON, 120000);
            recebidas++;
            //remoção de código para facilitar visualização
        }
    });
}

$(document).ready(CarregarJSON);

Eventually you can add the call to CarregarJSON (no timer, or shorter than 2 minutes) in case of error so calls immediately ajax again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.