简体   繁体   中英

Repeat JavaScript AJAX request until status change

I am using AJAX to make and retrieve an API call from PHP file and then using jQuery IF statements to display certain data.

The data returned come with a few different statuses, Eg: "Ready", "In progress", "DNS" and "Error". Each status has a message that comes with it.

For one particular status, "In progress", I want to keep cycling through the JavaScript function until the status changes to something else. If the status is "In progress", it can take up to 1 minute for it to change, so if possible, I would like to cycle through the JavaScript function in 5 second intervals.

I have included my jQuery below.

    $(document).ready(function() {

    //Stops the submit request
    $("#myAjaxRequestForm").submit(function(e){
           e.preventDefault();
    });

    //checks for the button click event
    $("#myButton").click(function(e){
           $("#ajaxResponse").empty();
            //get the form data and then serialize that
            dataString = $("#myAjaxRequestForm").serialize();

            //get the form data using another method
            var hostName = $("input#hostName").val();
            dataString = "host=" + hostName;

            //make the AJAX request, dataType is set to json
            //meaning we are expecting JSON data in response from the server
            $.ajax({
                type: "GET",
        url: "api.php",
                data: dataString,
                dataType: "json",

                //if received a response from the server
                success: function( response ){
                var data = response.status;
                    if ((data == 'READY' && response.endpoints[0].statusMessage == 'Ready' )) {
                    $("#ajaxResponse").append("<b>Status:</b> " + response.endpoints[0].statusMessage+ "<br>");
                    $("#ajaxResponse").append("<b>Host:</b> " + response.host+ "<br>");
                    $("#ajaxResponse").append("<b>Port:</b> " + response.port+ "<br>");
                    $("#ajaxResponse").append("<h3>Endpoint [0]</h3><b>Server Name:</b> " + response.endpoints[0].serverName+ "<br>");
                    $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[0].ipAddress+ "<br>");
                    $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[0].grade+ "<br>");
                    $("#ajaxResponse").append("<h3>Endpoint [1]</h3><b>Server Name:</b> " + response.endpoints[1].serverName+ "<br>");
                    $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[1].ipAddress+ "<br>");
                    $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[1].grade+ "<br>");
                    $("#ajaxResponse").append("<h3>Endpoint [2]</h3><b>Server Name:</b> " + response.endpoints[2].serverName+ "<br>");
                    $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[2].ipAddress+ "<br>");
                    $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[2].grade+ "<br>");
                     }
                    else if ((data == 'READY' && response.endpoints[0].statusMessage != 'Ready')) {
                        $("#ajaxResponse").append("<b>Status: </b>" +response.endpoints[0].statusMessage+ "<br>");
                        $("#ajaxResponse").append("<b>Server Name: </b>" + response.endpoints[0].serverName+ "<br>");
                        $("#ajaxResponse").append("<b>IP Address: </b>" + response.endpoints[0].ipAddress+ "<br>");
                     }
                     else if (data == "DNS") {
                         $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" +response.statusMessage+ "<br>..please wait a few mins and try again.</b></div>");
                     }
                     else if (data == "IN_PROGRESS") {
                         $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" +response.endpoints[0].statusMessage+ "<br>..please wait a few mins and try again.</b></div>");
                     }
                     else if (data == "ERROR") {
                         $("#ajaxResponse").html("<div><b>Error.<br><br>" +response.statusMessage+ "<br></b></div>");
                     }
                     else {
                         $("#ajaxResponse").html("<div><b>error</b></div>");
                     }
                },

            });       
    });

});

Move the AJAX request to a function (eg doAjax()) so that you can call it as needed. Call doAjax() when the button is clicked. When the status returned is "In Progress", use setTimeout() to recursively call the same function after 5 seconds.

The AJAX request will be made roughly every 5 seconds until the status is something other than "In Progress". (I say "roughly" because the AJAX request itself takes time and the 5 second delay starts AFTER the request is completed.)

Updated JavaScript:

$(document).ready(function () {

    //Stops the submit request
    $("#myAjaxRequestForm").submit(function (e) {
        e.preventDefault();
    });

    //checks for the button click event
    $("#myButton").click(function (e) {
        e.preventDefault(); // Prevent default button click action
        doAjax();
    });

});

function doAjax() {
    //$("#ajaxResponse").empty(); Move this to reduce appearance of refreshing
    //get the form data and then serialize that
    dataString = $("#myAjaxRequestForm").serialize();

    //get the form data using another method
    var hostName = $("input#hostName").val();
    dataString = "host=" + hostName;

    //make the AJAX request, dataType is set to json
    //meaning we are expecting JSON data in response from the server
    $.ajax({
        type: "GET",
        url: "api.php",
        data: dataString,
        dataType: "json",

        //if received a response from the server
        success: function (response) {
            var data = response.status;
            if ((data == 'READY' && response.endpoints[0].statusMessage == 'Ready')) {
                $("#ajaxResponse").empty();
                $("#ajaxResponse").append("<b>Status:</b> " + response.endpoints[0].statusMessage + "<br>");
                $("#ajaxResponse").append("<b>Host:</b> " + response.host + "<br>");
                $("#ajaxResponse").append("<b>Port:</b> " + response.port + "<br>");
                $("#ajaxResponse").append("<h3>Endpoint [0]</h3><b>Server Name:</b> " + response.endpoints[0].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[0].ipAddress + "<br>");
                $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[0].grade + "<br>");
                $("#ajaxResponse").append("<h3>Endpoint [1]</h3><b>Server Name:</b> " + response.endpoints[1].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[1].ipAddress + "<br>");
                $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[1].grade + "<br>");
                $("#ajaxResponse").append("<h3>Endpoint [2]</h3><b>Server Name:</b> " + response.endpoints[2].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address:</b> " + response.endpoints[2].ipAddress + "<br>");
                $("#ajaxResponse").append("<b>Grade:</b> " + response.endpoints[2].grade + "<br>");
            } else if ((data == 'READY' && response.endpoints[0].statusMessage != 'Ready')) {
                $("#ajaxResponse").empty();
                $("#ajaxResponse").append("<b>Status: </b>" + response.endpoints[0].statusMessage + "<br>");
                $("#ajaxResponse").append("<b>Server Name: </b>" + response.endpoints[0].serverName + "<br>");
                $("#ajaxResponse").append("<b>IP Address: </b>" + response.endpoints[0].ipAddress + "<br>");
            } else if (data == "DNS") {
                $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" + response.statusMessage + "<br>..please wait a few mins and try again.</b></div>");
            } else if (data == "IN_PROGRESS") {
                $("#ajaxResponse").html("<div><b>No cached result found.<br><br>" + response.endpoints[0].statusMessage + "<br>..please wait a few mins and try again.</b></div>");
                // Call this function again after 5 seconds
                setTimeout(function () {
                    doAjax();
                }, 5000);
            } else if (data == "ERROR") {
                $("#ajaxResponse").html("<div><b>Error.<br><br>" + response.statusMessage + "<br></b></div>");
            } else {
                $("#ajaxResponse").html("<div><b>error</b></div>");
            }
        },

    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM