Link to home
Start Free TrialLog in
Avatar of Øyvind Isaksen
Øyvind IsaksenFlag for Norway

asked on

Ajax run each second, get data from WebMethod

I have simple WebMethod that do some job and returns status. In my example, it only returns a number for testing.

Then I have an Ajax code that post to my webmethod. If I call the WebMethod directly, it returns data correct. But, if I call the WebMethod from inside setInterval(), the WebMethod don't return data. If I try to return a variable from inside the WebMethod, it works correct.

How can I run a WebMethod each second, until the WebMethod returns wanted result?


<script type = "text/javascript">
    var counter = 5;

    var Pull = function (c) {
        var data = JSON.stringify({ count: c });

        $.ajax({
            type: "POST",
            url: "Accepted.aspx/Receipt",
            contentType: "application/json; charset=utf-8",
            data: data,
            dataType: "json",
            success: PullSuccess,
            error: OnError
        });

    }

    function PullSuccess(response) {
        $("#<%= lbl.ClientID %>").text(response.d);
    };

    function OnError(response) {
        $("#<%= lbl.ClientID %>").text("Error occured");
    };

    function countdown() {
        var interval = setInterval(function () {

            counter--;
            if (counter <= 0) {
                clearInterval(interval);
                $("#<%= lbl.ClientID %>").text("Done");
            } else {

                Pull(counter);
            }

        }, 1000);
    }

    countdown();

    // Works fine:
    // Pull(5);

</script>


[System.Web.Services.WebMethod]
public static int Receipt(int count)
{
    return count;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Øyvind Isaksen

ASKER

Thanks for your reply. I have tested the code, but the label "lbl" only display "5". Expected result should be that the number decrease each second.

After some research, it seems like the error is caused by no support for 'let' and 'const' (ECMAScript 6) in my project. Can your code be made without using 'let' and 'const'?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you Michel, now everything works perfect.