Reputation: 179
I would like to make an Ajax request to the server, which replies a job status and result. If the status is "Error" or "Ok", the client should show the result (containing HTML code) to the user. However, if the status is "Waiting", the client should wait for a few seconds and then automatically send the same Ajax request again. This should continue until it either times out or gets a "Error"/"OK" message.
Any idea for a solution/code snippet like this? I am currently using Rails, JQuery, and Prototype. Many thanks.
Mountain
Upvotes: 0
Views: 472
Reputation: 1051
Javascript:
var t = setInterval('checkServer', 5000)
function checkServer() {
$.ajax({
url: 'yoururl',
data: params,
success: function(resp) {
if(resp == "Error" || resp == "OK") {
alert(resp);
clearInterval(t);
}
}
});
}
Upvotes: 0
Reputation: 7477
Without fully understanding the context of your application I would think you need to make sure that getting the response from the server is not critical is that you may not necessary rely on the retry to occur in the "Waiting" response case. For example, if the user navigates away from the page the script may be unloaded and the retry would not then occur.
If, as it seems, you are anticipating possibly long running jobs it might be best just to return a HTTP status OK and allow the content to be retrieved at a later point either synchronously or asynchronously as appropriate.
You might also consider delivering the response using HTTP header attributes rather than inlined with your response data.
Upvotes: 0
Reputation: 236202
You can do like
(function refresh(){
$.ajax({
url: '/myfile',
data: 'data',
dataType: 'text',
type: 'POST',
success: function(data){
if(data === 'Waiting')
setTimeout(refresh, 5000);
else
alert(data);
}
});
})();
That would initiate a self-executing anonymous function
with an ajax request. If the returned string equals Waiting
it will set a timeout for 5 seconds and calls itself again.
Upvotes: 2