Øyvind Isaksen
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?
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;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you Michel, now everything works perfect.
ASKER
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'?