Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to repeat ajax call until success

Tags:

jquery

When the button "getproduct" is clicked, the ajax call get the product or the 404 code if the product is not avaible.

I want the function getMyJson being call again every 5 seconds until the product is returned.

Any ideas ?

$(function () {
    $("#getproduct").click(function getMyJson() {
        $.ajax({
            type: "GET",
            url: "Product/GetProduct",
            dataType: "json",
            success: function (data) {
                //alert("succes");
                $("#name").html(data.Name);
                $("#price").html(data.Price);
            },
            error: function () {
                //alert("fail");
                //callback getMyJson here in 5 seconds
            }
        });
    });
});
like image 510
Maxime Avatar asked Dec 14 '13 12:12

Maxime


1 Answers

You can use setTimeout in error callback function

$(function () {
    function getMyJson() {
        $.ajax({
            type: "GET",
            url: "Product/GetProduct",
            dataType: "json",
            success: function (data) {
                //alert("succes");
                $("#name").html(data.Name);
                $("#price").html(data.Price);
            },
            error: function () {
                //alert("fail");
                //callback getMyJson here in 5 seconds
                setTimeout(function () {
                    getMyJson();
                }, 5000)
            }
        });
    }
    $("#getproduct").click(function () {
        getMyJson();
    });
});
like image 134
Satpal Avatar answered Oct 19 '22 03:10

Satpal