Javascript status loop - javascript

Ok, simple thing in javascript that I could not solve even searching on the web. I guess I even found the right thing but could not put on the right place.
This code tells me if a stream is online or offline. But how do I do to the status and keep updating every 5 seconds?
$(function () {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else {
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
});

Example :
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
var ResInterval = window.setInterval(myAjaxCall, 60000); // 60 seconds
To Stop:
window.clearInterval(ResInterval);

use set time out function
setTimeout(function(){
//your function
foo();
},1000);

Try this out:
function checkStatus() {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else{
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
}
$(function() {
setInterval(checkStatus, 5000);
});
This calls the function checkStatus every 5000 milliseconds (5 seconds).

Related

How to invoke a method from ajax success function?

I've a jQuery with ajax using to fetch some data from a servlet
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: function(response){
//some data fetched from ServiceToFetchDocType
//Need to invoke another method here
}
});
</script>
Is it possible to invoke another method inside the success function and get some value?
I've very new to jQuery and ajax, any kind of help is appreciated.
$(document).ready(function() {
$.ajax({
url: 'ServiceToFetchDocType',
type: 'post',
cache: false,
success: function(response) {
/* invoke your function*/
yourFunction();
}
});
});
you can do something like this
var invokeAfterSuccess = function() {
}
var successFunction = function(response) {
/* do something here */
invokeAfterSuccess()
}
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: successFunction
})
/*--------------- OR -------------*/
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false
}).done(successFunction)
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: function(response){
Myfunction(); //this is how you can call function
}
});
Myfunction(){
alert("hiii")
}
}
</script>
// thats how it will work
[success: function (data) {
TypeOfReportDropdown.closest("form").find("div\[id$='MonitoringChemicalData'\]")\[0\].innerHTML = data;
var hours = $("#UptimeHourYear").val();
var emissions = round(parseFloat(($("#AverageMassLoadOut").val() * hours) / 1000), 1);
$("#Emissions").val(emissions);
$("#TotalEmissions").val(emissions);
$(this).delay(3000).queue(function () {
var emissieTotal = 0;
var totalHAP = 0;
$('\[data-emissie\]').each(function () {
emissieTotal += Number($(this).data('emissie'));
var hap = $(this).data('hap');
if (hap == "True") {
totalHAP += Number($(this).data('emissie'));
}
});
var emissieFinalTotal = round(emissieTotal, 3);
$('#TotalEmissionForOnlineInstruments').html(emissieFinalTotal);
var totalHAPFinal = round(totalHAP, 3);
$('#TotalHAPForOnlineInstruments').html(totalHAPFinal);
});
}][1]

jQuery clearinterval / stopinterval doesn't work

I have an autorefresh function that gets called if a checkbox is checked and a button clicked. I want to stop the autorefresh when the checkbox is unclicked:
var refreshId = null;
$("#disINFRAlive").click(function(infralivefun) {
event.preventDefault(infralivefun);
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
if ($('#autorefcheck').is(':checked')) {
var refreshId = setInterval(function() {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['datumend'] = $("#datumend").datepicker().val();
$.ajax({ //create an ajax request to display.php
type: "POST",
url: "infratestomc.php?id=" + Math.random(),
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttabelle").show().html(response);
}
});
}, 5000);
}
});
The autorefresh works if the checkbox #autorefcheck is checked and the button #disINFRAlive is clicked. However, I can't make it stop by unchecking the checkbox:
function stopinterval(){
clearInterval(refreshId);
return false;
}
$('#autorefcheck').click(function() {
stopinterval();
});
I tried to use clearInterval in various ways and none worked so far.
Remove the var keyword from the initialization of refreshId.
if ($('#autorefcheck').is(':checked')) {
refreshId = setInterval(function() {
The way you have it, you are redeclaring the variable in a different scope. That way, you cannot access it from stopInterval().

How to stop setInterval in a do while loop in jquery

I want to do is stop setInterval after the do while loop meet the condition.
My problem is even the while loop condition is meet the setInterval is still running.
do
{
setInterval(
Vinformation();
,500);
}while($('#emailCodeResult').val() !='')
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
}
});
return false;
}
You don't need while loop here at all. In combination with setInterval it doesn't make sense. What you need is probably just setInterval:
var interval = setInterval(Vinformation, 500);
function Vinformation() {
if ($('#emailCodeResult').val() == '') {
clearInterval(interval);
return;
}
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType: "JSON",
success: function (result) {
}
});
}
Use clearInterval function to stop interval.
Also note, that setInterval expects function reference as the first argument so this setInterval(Vinformation(), 500) is not correct, because you immediately invoke the Vinformation function.
var itvl1= window.setInterval(function(){
Vinformation();
},500);
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
if(data.emailCodeResult !=''){
window.clearInterval(itvl1);
};
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"Jenter code hereSON",
success: function (result) {
}
});
return false;
}

How to check json response taken longer than 5 seconds?

Below is the sample code of my function. in the for loop one by one product id is pass in the ajax function and get product price from the php file as response and write it and html.
for(var i=0; i < data.products.length; i++){
var doc = data.products[i];
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
success: function(data)
{
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
}
I have found that sometimes it takes a more time for price to display. i want to check which record is taking time to load. how can check to detect when it takes longer than 5 seconds for the price to load?
Something like this....
var ajaxTime= new Date().getTime();
$.ajax({
type: "POST",
url: "some.php",
}).done(function () {
var totalTime = new Date().getTime()-ajaxTime;
// Here I want to get the how long it took to load some.php and use it further
});
Also, by the way, if you want to prevent sending (i+1) request, before (i) is completed, you'd maybe want to use syncronous ajax request instead of async.
Try to log timestamp beforesend and success or error
$.ajax({ // ajax call starts
url: 'product.php',
data: { product_id: doc.id },
dataType: 'json',
beforeSend: function() {
console.log(new Date().getSeconds());
}
success: function(data)
{
console.log(new Date().getSeconds());
document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
}
});
Use setTimeout, like this:
var timeoutTimer = setTimeout(function() {
// time out!!!.
}, 5000);
$.ajax({ // ajax call starts
url : 'product.php',
data : {
product_id : doc.id
},
dataType : 'json',
success : function(data) {
document.getElementById('price_price' + data.product_id + '').innerHTML = data.products_price;
},
complete : function() {
//it's back
clearTimeout(timeoutTimer);
}
});

Javascript when to show results

This is my Javascript below I want to show records on load and also show new records when added to the database
showrecords(); displays the records in the database where abouts can I put this in my code where it will work correctly.
$(document).ready(function()
{
//showrecords()
function showrecords()
{
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
}
});
}
$(".comment_button").click(function() {
var element = $(this);
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
// $("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
//Function for showing records
//showrecords();
}
});
}
return false;
});
});
Though polluting the global namespace is not recommended. Here is what I would recommend for your code. Move the showRecords() out of Document ready function and refactor the update ajax code to another function 'updateRecords()'. Have only the event bindings inside the document ready function.
You could return the entire comments as response to POST 'demo_insert.php' service and call 'showRecords()' in the update service success callback.
i've pasted below (untested) code that i think should get the job done. in order to call functions you've got to define them in an accessible area, whether in the "global" (can be called from anywhere) namespace as i've done below, or as part of an another object.
you also need to make sure your functions are defined before you try to call them, as everything works in a top down manner.
function showrecords() {
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function (html) {
$("#display").after(html);
$('content').val('');
$("#flash").hide();
}
});
}
function addComment() {
var test = $("#content").val();
var dataString = 'content=' + test;
if (test == '') {
alert("Please Enter Some Text");
}
else {
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function (html) {
//$("#display").after(html);
$('content').val('');
$("#flash").hide();
//Function for showing records
showrecords();
}
});
}
}
$(document).ready(function () {
showrecords()
$(".comment_button").click(function () {
addComment();
return false;
});
});

Categories

Resources