I have a button on my webpage. If a user clicks it, a task starts and returns a ID. I want to use this ID to check the progress of the task in another ajax call, to let the user know if the task was completed.
I have tried this, but I don't think it is the correct way:
<script type="text/javascript">
$(document).ready(function() {
$('#get-user-transactions').click(function() {
$( "#user-transactions" ).after( "<p>Loading data</p>" );
$.ajax({
url: "/start-task/",
dataType: "json",
success: function(data){
if(data) {
var stateCheck = setInterval(
$.ajax({
url: "/check-taskstate/"+data.task_id,
dataType: "json",
success: function(data){
if (data.updated == 'true') {
clearInterval(stateCheck);
window.location.reload();
}
}
})//ajax
, 1000); //stateCheck
}
}
})//ajax
});
});
</script>
I updated my code, so the first url also gives a json response. But If I try my code I get this error:
Uncaught SyntaxError: Unexpected identifier
Since setInterval()
accepts a function or code but you are passing an jqXHR object you must be getting error for that.
func is the function you want to be called repeatedly
code in the alternate syntax, is a string of code you want to be executed repeatedly (using this syntax is not recommended for the same reasons as using eval())
Use
var stateCheck = setInterval(function(){
$.ajax({
url: "/check-taskstate/"+data.task_id,
dataType: "json",
success: function(data){
if (data.updated == 'true') {
clearInterval(stateCheck);
window.location.reload();
}
}
});
}, 1000); //stateCheck