I have the following code to ping a list of computers with Jquery and asp.net.
function ping() {
$('#progress').css("display", "");
$('.comp').each(function () {
var $computer = $(this);
$.getJSON('pingcomputer.aspx', { computer: $(this).attr("rel") }, function (data) {
if (data.Status == '1') {
$($computer).attr("src", "ok.png");
}
else {
$($computer).attr("src", "nok.png");
}
})
})
$('#progress').css("display", "none");
}
The pinging works fine.
Before the ping start I want to make #progress visible (an image)
After all computers are pinged I want to hide it again.
The problem is that the #progress image is immediately hidden when the function is called.
How can I detect when all "pingcomputer.aspx" pages have finished loading?
Add a counter which checks that as many requests have been completed as there was started:
function ping() {
$('#progress').css("display", "");
var count = 0,
total = $(".comp").length;
$('.comp').each(function () {
var $computer = $(this);
$.getJSON('pingcomputer.aspx', { computer: $(this).attr("rel") }, function (data) {
count++;
if (data.Status == '1') {
$($computer).attr("src", "ok.png");
}
else {
$($computer).attr("src", "nok.png");
}
if (count==total) $('#progress').css("display", "none");
})
})
}
Count the number of things that should happen, decrement the count each time one thing does. When there are none left, stop the progress bar. BTW, any reason you're not using show()/hide()?
function ping() {
$('#progress').show();
var $comp = $('.comp'),
waitCount = $(comp).length;
$comp.each(function () {
var $computer = $(this);
$.getJSON('pingcomputer.aspx', { computer: $(this).attr("rel") }, function (data) {
if (data.Status == '1') {
$($computer).attr("src", "ok.png");
}
else {
$($computer).attr("src", "nok.png");
}
if (--waitCount == 0) {
$('#progress').hide();
}
})
})
}
Related
I currently have a problem,
I have a client who wants his site in Argentina to be seen only in Argentina and that users entering from another country are redirected to the official website in France, and that when the API query is made if you are inside Argentina, the geolocation script is not executed It should be noted that the only way,the api that I am using is ip api, I have to create it in js. Because the system we are using does not give us access to server. and additionally a cookie must be saved. So I did the following.
var site = {
init: function() {
this.setDisplayClass();
this.global();
this.search();
this.newsletter();
menu.init();
minicart.amount(".cart-link .qty-items");
minicart.create();
minicart.hover();
if ($('body').hasClass('home')) {
banner.background('.main-banner-section .box-banner');
banner.slide('.run-slick');
shelf.slide('.featured-products-slider .shelf ul');
}
if ($('body').hasClass('grid-products')) {
grid.init();
}
if ($('body').hasClass('producto')) {
product.init();
shelf.slide('#related-products .shelf ul');
}
},
}
AND
var geo ={
init: function(){
var isAr = localStorage.getItem("country");
if((isAr == null) || (isAr == undefined)){
$.ajax({
url: 'http://ip-api.com/json/?callback=?',
async: false,
dataType: 'jsonp',
success: function (response) {
var country = response.countryCode;
if(country !== "AR"){
window.location.replace("https://www.google.com.ar");
}else{
localStorage.setItem('country', country);
if($(".loading-hidden").length > 0){
$(".loading-hidden").each(function(){
if ($(this).attr('style') == 'visibility: hidden;') {
console.log(1);
site.init();
$(this).removeAttr('style');
if ($("#loading").length > 0) {
$("#loading").remove();
}
}
});
}
}
}
});
}else{
if ($(".loading-hidden").attr('style') == 'visibility: hidden;') {
site.init();
$('.loading-hidden').removeAttr('style');
if ($("#loading").length > 0) {
$("#loading").remove();
}
}
}
}
}
AND
$(document).on('ready', function() {
});
site.init();
$(window).bind("load", function() {
});
The error I get is that site.init is undefined.
I have the following code:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
window.setInterval(function(){
refreshChat();
}, 2000);
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});
</script>
Right now, the refreshChat function calls an ajax script every 2 seconds. When you have entered a message and press enter, it calls a different ajax script. What I would like it to do, is call both functions at the same time. So the script calls the sendMessage function first and refreshes afterwards.
How can I do this? I have already tried changing it to:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();refreshChat();
}
});
</script>
But this only enters the message first, and it only refreshes on the second keypress (enter). I would like to thank everybody beforehand on helping me out.
This is actually an illusion. Both functions are being called, but the chat window is refreshing before the chat message is able to save them.
To fix this, you should refresh the chat window only once the new message has been successfully saved:
function refreshChat() {
// Removed for brevity
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
// Now, this will only be called once the ajax is complete
refreshChat();
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
// I removed the refreshChat() call from here and moved it
// into the $.get() callback above ^^
}
});
As you can see, I moved your refreshChat() method to now be called from within the jQuery $.get() callback.
Have you tried using callbacks, that may be what you need?
Here is a link for reference.
http://www.impressivewebs.com/callback-functions-javascript/
MY WORKING AWNSER
Considering for what i asked, i have marked Wes Foster's awnser as correct. What made it work for me is also applying a promises after the get function. This way, the ajax script get's called twice as needed. I hope it will help someone in the future. (Look at me... travelling through time...). You will find my code underneath:
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
refreshChat();
}).done(refreshChat);
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});
So I've been stuck at this problem for quite a long time. Basically I have a button (#action) located in index.html. I have a second page : number.html. I'm trying to get in the .receiver span from index.html either .success content or .failure content from number.html, depending if #action was clicked in less than 2 seconds.
Here is the code :
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
});
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
});
Problem : on click, I never get the .success content, and I have no error message. But after 2 seconds, the .failure actually shows up. I tried several ways to make it work but it doesnt. I also checked if the flag value was changed on click with an alert box, and it was
You need to include the ajax calls within the on click function, otherwise the if logic will only be called when the page is loaded and never again.
$(function() {
var ajaxRetrieve = function(callback) {
$.ajax({
url: 'number.html',
method: 'POST',
success: function(responseData) {
callback(responseData);
},
error: function(responseData) {
alert('Check yourself');
}
});
}
var flag = 0;
$('#action').on('click', function() {
flag = 1;
flagCheck();
});
var flagCheck = function() {
if (flag == 1) {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.success'));
});
} else {
setTimeout(function() {
ajaxRetrieve(function(data) {
$('.receiver').html($(data).find('.failure'));
});
}, 3000);
};
}
});
function getFriends(url) {
return FB.api(url, function(response) {
if (response && !response.error) {
if (response.paging && response.paging.next) {
$.each(response.data, function() {
friends.push(this);
});
return getFriends(response.paging.next);
} else {
console.error(friends);
}
} else {
console.error("facebook friends couldn't been retrieved ");
}
});
}
$.when(getFriends("/me/friends")).then(
function() {
console.log('getFriends finished');
});
i want to make sure that fb calls finished when the then() block executed but had no chance. is there a way to implement this ?
thanks
The Facebook JS SDK does not implement jQuery style promise objects / $.Deferreds but you can easily create an instance on your own like:
function getFriends(url) {
var dfd = $.Deferred();
FB.api(url, function(response) {
if (response && !response.error) {
if (response.paging && response.paging.next) {
$.each(response.data, function() {
friends.push(this);
});
return getFriends(response.paging.next);
} else {
console.log(friends);
}
dfd.resolve();
} else {
console.error("facebook friends couldn't been retrieved ");
dfd.reject();
}
});
return dfd;
}
getFriends("/me/friends").done(
function() {
console.log('getFriends finished');
}
);
Not really an answer, but a working example that demo's how to go about it:
Demo JSFiddle
function doStuff() {
var dfd = new jQuery.Deferred();
alert ("loaded");
setTimeout(function(){
dfd.resolve("response - success");
}, 5000);
return dfd.promise();
}
$.when(doStuff()).then(function(status) {
alert(status);
});
When there is an update from getjson, the textbox text changed!
No allert is comminh up.. some one can help me with this allert??
The textbox:
<input id="your_textbox" />
setInterval(function () {
$.getJSOg('/api/my_apiurl', function (Payload) {
$(Payload).each(function (i, item) {
$("#your_textbox").val(item.CR_DateTime);
});
});
}, 3000);
and the script to allert "haai:
setInterval(function () {
jQuery('#your_textbox').on('input', function () {
alert('haai');
});
}, 3000);
Change to (not working):
setInterval(function () {
var check;
$(function(checkForMessages) {
$.getJSON('/api/myapiurl', function (data) {
if(data == 1) {
//There are new messages
clearInterval(check);
alert("You have mail!");
}
}
);
check = setInterval(checkForMessages, 3000);
});
}, 3000);
You keep adding an even to the textbox over and over and over again! That is really bad.
It should just be
jQuery('#your_textbox').on('input', function () {
alert('haai');
});
Now JavaScript does not trigger the event when you change the textbox with code, so you need to do the triggering.
var previousValue = $("#your_textbox").val(),
newValue = item.CR_DateTime;
if (previousValue !== newValue ) {
$("#your_textbox").val(newValue).trigger("input");
}