How to stop ajax timer if results contains key - javascript

I have a simple ajax function:
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function crunchifyAjax() {
$.ajax({
url: '/user/show-user-task-messages?code=<c:out value="${liveCode}"/>',
success: function (data) {
$('#result').html(data);
}
});
}
</script>
<script type="text/javascript">
var intervalId = 0;
intervalId = setInterval(crunchifyAjax, 100);
</script>
The function check every 100ms my url and return some text like this:
10
9
8
7
6
5
4
3
2
1
stop
I want to break this timer after data contains stop. How can I do this?
Any help in this regard is much appreciated.

Try this:
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function crunchifyAjax() {
$.ajax({
url: '/user/show-user-task-messages?code=<c:out value="${liveCode}"/>',
success: function (data) {
$('#result').html(data);
if((""+data).indexOf("stop") > -1)
clearInterval(intervalId); //clearing the interval started by setInterval
}
});
}
</script>
<script type="text/javascript">
var intervalId = 0;
intervalId = setInterval(crunchifyAjax, 100);
</script>

Just to give you an example, check for data's content - and if it matches your condition (in your case holding "stop") -> clearInterval().
Dummy code:
var intervalId = null;
var x = 0;
intervalId = setInterval(crunchifyAjax, 100);
function crunchifyAjax() {
if (x < 10) {
x++;
console.log(x);
return true;
}
clearInterval(intervalId, crunchifyAjax);
}

Assuming your server returns an array of items like
["1","2","4","stop","6"]
You can check the array coming back and see whether it has an item "stop" and if yes call clearInterval method.
success: function (data) {
$('#result').html(data);
var subset = data.filter(function (a) {
return a === "stop";
});
if (subset.length > 0) {
window.clearInterval(intervalId);
}
}
If your server is returning a string like "1,3,5,stop,6", you can do indexOf method to check the existence of the specific string
success: function(data) {
$('#result').html(data);
if (data.indexOf("stop") > -1) {
window.clearInterval(intervalId);
}
If you are returning a collection of items, I strongly suggest you to return an array instead of a concatenated string.

Related

How to create javascript while loop that breaks when value from JSON url is not null?

I have the following code which reads from a url. I'd like create a while loop that runs continuously every second until data does not equal null
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
$.getJSON("https://bnb.firebaseio.com/airbunny/listing_rank_data/16861909NULL.json", function(data) {
console.log(data)
});
Here is my attempt:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
$.getJSON("https://bnb.firebaseio.com/airbunny/listing_rank_data/16861909NULL.json", function(data) {
while (data=='null') {
setTimeout(function (){
}, 5000);
}
console.log(data)
});
No need of while loop here. You can create a function which can be executed with delay using setTimeout
function getData(){
$.getJSON("https://bnb.firebaseio.com/airbunny/listing_rank_data/16861909NULL.json", function(data) {
if(data == null){
setTimeout(getData, f000);
} else {
console.log(data);
}
});
}
//Initial Invocation
getData();
You could try the setTimeout method:
function poll() {
$.getJSON("https://bnb.firebaseio.com/airbunny/listing_rank_data/16861909NULL.json", function(data) {
if (data === "null") {
// The data is null, send a new request in 5 seconds
window.setTimeout(poll, 5000);
} else {
// The data is no longer null, we don't need to continue polling
console.log(data);
}
});
}

recall ajax in click event

$function(){ and $window.onload() - I'm not sure how to handle this? On the $('#ashift').on('click',function(){ I need the ajax call to fire again? should I wrap it in a function and call the function on page load and then again in the click event, or is there a better way - I need the clicked_shift variable to update in the ajax call.
<script id="source" language="javascript" type="text/javascript">
var clicked_shift = "C";
$('#ashift').on('click', function(){
clicked_shift = "A";
});
$(function () {
$.ajax({
url: 'county.php',
data: {action:"tt"},
dataType: 'json',
success: function(data){
alert(clicked_shift);
$.each(data, function(key, val) {
if (val.completed == 1) {
color = "green";
} else {
color = "red";
}
if (val.Shift == clicked_shift){
$('#station'+val.Station+' .snum').append("<span style='color:"+color+"'>" + val.LastName + "</span><br/>");
}
});
}
}); // end ajax
}); // end of function()
</script>
var clicked_shift = "C";
function ajaxCall(){ // function declaration
console.log("clicked_shift",clicked_shift);
}
$(function () {
ajaxCall(); // call function ondomready
$('#ashift').live('click',function(){
clicked_shift = "A"; // change variable value
ajaxCall(); // re-invoke the function
});
}); // end of function()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="ashift">click</div>
$(function(){}); is like $(document).ready(function(){}); a self invoked anonymous function which will be triggered when dom is fully loaded. To re-invoke a function later, you need to declare it or to assign it to a variable.`

Open window after script execution

Is it possible to open the window after the execution of the script expandNextLevel()?
I'm asking this because I don't want to let the client see the expand/collapse animation but just the treeview collapsed.
This is my code.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel();
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel();
collapseNextLevel();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
Regards
try this
$.when(expandNextLevel()).done(function(){
/// show window
});
docs https://api.jquery.com/jquery.when/
I think the fastest way to do something like this is put everything in a hidden div, wich you will then show when you're done with the code execution.
You could also put a visible div with a rotating icon while the code is being executed, and hide it when you show the main content to make the users know something is happening.
EDIT:
I made a slight modification to the expand function, that should let me know when it's done executing the recursion, by adding an index I increment everytime. At the end of the function there is a code that will be executed only when the index is equal to one, wich means the first instance of the function is done executing.
<script type="text/javascript">
$(function () {
$(".k-gantt").click(function () {
expandNextLevel(0);
var windowWidget = $("#window");
windowWidget.data("kendoWindow").open().center();
$.ajax({
type: 'GET',
url: '/Act/load',
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
function expandNextLevel(var i)
{
i++;
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-plus').length;
treeview.expand(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
expandNextLevel(i);
collapseNextLevel();
}
if (i == 1)
{
$.("#maincontent").show();
}
}
, 200);
};
function collapseNextLevel()
{
setTimeout(function () {
var treeview = $("#treeview").data("kendoTreeView");
var b = $('.k-item .k-minus').length;
treeview.collapse(".k-item");
treeview.trigger('dataBound');
if (b > 0) {
collapseNextLevel();
}
}
, 200);
};
</script>
You should put you content inside a div
<div id="maincontent" style="display:none;">
/*your content*/
</div>
I didn't test it but it should work :)
There is a better way to do this with jQuery.when, jQuery.done and promises, but I'm not confident I can give you a working sample since I never used those methods

getJson after getJson not working

I'm trying to make a request when the button is clicked.
If it is the first time clicking it, I make a getJson to get an array with the IDs for the second request.
The problem is, when it makes the first request, it stops right before the second request, so I have to click again to make the second request.
Here is my script code:
<script type="text/javascript">
$(document).ready(function() {
var IDs = new Array();
var iterator = 0;
// When id with Action is clicked
$("#Action").click(function() {
if(IDs.length <= 0){
// Load generator.php as JSON and assign to the data variable
$.getJSON('generator.php', {tags : "lol"}, function(data) {
IDs = data.value;
});
}
//PAGE STOPS HERE
$.getJSON('imagem.php', {ids : IDs[iterator]}, function(data) {
iterator++;
document.title = "IMG2";
$("#Imagem").html(data.value);
if(iterator > IDs.length-1)
iterator = 0;
});
});
});
</script>
The $.getJson() function is asynchronous. This means that when it executes that bit of code, it continues on with execution. The second call depends on the first one so should be nested in the success callback like this:
$.getJSON('generator.php', {tags : "lol"}, function(data) {
IDs = data.value;
$.getJSON('imagem.php', {ids : IDs[iterator]}, function(data) {
iterator++;
document.title = "IMG2";
$("#Imagem").html(data.value);
if(iterator > IDs.length-1)
iterator = 0;
});
});
From your code visiting, we think -
It is a typical case of ajax call ...
to make the 2nd call after 1st call, you should call the 2nd getjson within 1st getjson callback to make this working - i.e. -
<script type="text/javascript">
$(document).ready(function() {
var IDs = new Array();
var iterator = 0;
// When id with Action is clicked
$("#Action").click(function() {
if(IDs.length <= 0){
// Load generator.php as JSON and assign to the data variable
$.getJSON('generator.php', {tags : "lol"}, function(data) {
IDs = data.value;
$.getJSON('imagem.php', {ids : IDs[iterator]}, function(data) {
iterator++;
document.title = "IMG2";
$("#Imagem").html(data.value);
if(iterator > IDs.length-1)
iterator = 0;
});
});
}
});
});
</script>
I have faced same situation before, for ajax calling in different applications. Hope this help you.
This is because $getJSON is an async event, so both your $getJSON function calls are happening at once, and your second requires results from the first. Please use the success event from jquery: http://api.jquery.com/jQuery.getJSON/
example from the above website:
$.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); });
New Code:
<script type="text/javascript">
$(document).ready(function() {
var IDs = new Array();
var iterator = 0;
// When id with Action is clicked
$("#Action").click(function() {
if(IDs.length <= 0){
// Load generator.php as JSON and assign to the data variable
$.getJSON('generator.php', {tags : "lol"}, function(data) {
IDs = data.value;
}).success(function() {
$.getJSON('imagem.php', {ids : IDs[iterator]}, function(data) {
iterator++;
document.title = "IMG2";
$("#Imagem").html(data.value);
if(iterator > IDs.length-1)
iterator = 0;
});
});
}
});
});
</script>

How do i timeout a jquery script thats set to run every second after half an hour?

I have a jQuery script that runs a function every second with setinterval. But i want to set a timeout for that so after half an hour it kills the script. How do i do this? Thanks :)
source code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
//var ID = $(this).attr("id");
var ID = '1';
if(ID){
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").prepend(html);
$("#more"+ID).remove();
}
})
}
return false;
}
</script>
<style>
Use this pattern:
var timer = null;
$(function() {
timer = setInterval(oneSecondFunction, 1000);
setTimeout(function() { clearInterval(timer); }, 30*60*1000);
});
Save the timer it creates when you do setInvterval and clear the interval after 30 minutes.
I.E.
var t = setInterval(oneSecondFunction, 1000);
setTimeout(function() { clearInterval(t); }, 30*60*1000);
you can do this:
<script type="text/javascript">
$(function() {
var interval= setInterval(oneSecondFunction, 1000);
setTimeout(function(){clearInterval(interval)}, 18000000); //half an hour
});
...
</script>
<style>

Categories