troubleshooting Question

Ajax run each second, get data from WebMethod

Avatar of Øyvind Isaksen
Øyvind IsaksenFlag for Norway asked on
C#ASP.NETAJAX
4 Comments1 Solution62 ViewsLast Modified:
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;
}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 4 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros