If NewMessage changes, I want an alert. I have tried live and change on and bind change, but nothing works.
Relevant PHP:
$message=6;
$myReturnData["Message"] = $message;
//JSON-encode and return
print json_encode($myReturnData);
Relevant jQuery:
setInterval(function(){
$.getJSON("foo.php", function(data){
var NewMessage=(data.Message);
if(NewMessage>0){
document.title= NewMessage + ' pm';}
$(NewMessage).live("change", function() {
alert(NewMessage);
});
});
}, 3000);
'change' is not doing what you think it should be. You should store the original message in a variable, then compare it to the new message you're getting. Like this:
var currentMessage = '';
setInterval(function(){
$.getJSON("foo.php", function(data){
var NewMessage=(data.Message);
if(NewMessage>0){
document.title= NewMessage + ' pm';
if (currentMessage !== NewMessage) {
alert(NewMessage);
currentMessage = NewMessage;
}
}
});
}, 3000);
Assuming you want function X to run when a variable controlled by the server changes. To that means you are using a polling mechanism.
So if you want your code to know when it receives a different message, you must store the previous message somewhere outside the scope of your callback function.
Most easy way:
var lastMessage = 'the server will never ever forever ever return this message';
setInterval(function(){
$.getJSON("foo.php", function(data){
// .. arbitrary code
if (lastMessage != data.Message)
{
alert('it changed');
lastMessage = data.Message;
}
// .. more arbitrary code
});
}, 3000);
i don't think the following code makes any sense or would even remotely work, because the NewMessage is not a DOM element, is it?
$(NewMessage).live("change", function() {
alert(NewMessage);
});
Related
i am using smoke.js which allows to style the classic alert javascript windows.
All you have to do is place .smoke before the alert ie. smoke.confirm()
The issue I am having is with the ok/cancel callback, it isnt working for me.
This is the example the website shows.
`You can implement these the same way you'd use the js alert()...just put "smoke." in front of it.
The confirm() replacement, however, needs to be used just a little differently:
smoke.confirm('You are about to destroy everything. Are you sure?',function(e){
if (e){
smoke.alert('OK pressed');
}else{
smoke.alert('CANCEL pressed');
}
});
and the code I have is;
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message)) {
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
It shows the style button and everything but when i click on OK it doesnt perform the function above, nothing happens.
So i rewrote it to
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message, function(e))) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}}
But now when i click it doesnt even show anything
I am not a programmer, Help!!!!!
If you want to try it go to latinunit.org login with david:123321 and then go to a post and try to add it to your favourites
Update
I tried the following, it shows the window but it doesnt perform the function;
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}})
return false;
});
Here is the js file of the smoke script Link
When i click on cancel the following shows;
Uncaught TypeError: Property 'callback' of object # is not a
function Line:198
Uncaught TypeError: Property 'callback' of object # is not a
function Line:208
The following is what's on those linesof the smoke script;
finishbuildConfirm: function (e, f, box)
{
smoke.listen(
document.getElementById('confirm-cancel-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(false);
}
);
smoke.listen(
document.getElementById('confirm-ok-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(true);
}
);
The builtin javascript alert/confirm functions are synchronous, this is not. You need to handle the result of the confirm using the javascript callback pattern. You pass a function to the smoke.confirm() function which called when you need to respond to an action.
See the following code. The if around the smoke.confirm() has been removed and the handling code is wrapped in the function passed to the smoke.confirm() function.
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}
});
}
I highly recommend reading a little about the callback pattern in javascript. It's very common and understanding it will help you use this plugin and many others.
I've recently started learning jQuery and I'm trying to make a little messaging system, I've gotten the messages to update every 2 seconds. However, I don't want the messages to update if there aren't any new messages. This is my current message updating code.
$(document).ready(function () {
setInterval(function() {
$.get("get_messages.php", function (result) {
if ($('.messages').html() != result){
$('.messages').html(result);
}
});
}, 2000);
});
The if statement doesn't seem to be working even though the div and result should be the same.
I hope that you have timestamp or messageID on server that could tell your script if there are new messages after last check.
ex.
var lastMessageID = 0;
function checkMessages(){
$.ajax(url,{
data:{
last_message_id:lastMessageID
},
success:function(data){
// Count new messages
if (Object.keys(data).length > 0){
$.each(data,function(index, item){
$('.messages').prepend("<span class='message'>"+item.message+"</span>");
});
// We suggest that this is our last message
lastMessageId = data[Object.keys(data).length-1].id;
}
}
});
}
var intervalM = setInterval(function(){
checkMessages();
},2000);
And please save some trees by using gziped JSON data. :)
I'm trying to run a function in JQuery that basically shuts down or starts up a server. The code I have so far is this -
$(".stopServer").click(function(){
$.post("controller.php",{stop: 'true', server: this.name});
$('#test'+this.name).load('controller.php?status=true&server='+this.name);
});
The problem is obviously it stops the server fine but it updates the status div ('#test'+this.name) straight away. This is no good because the server takes a period of time to shut down. I've been trying to get SetTimeout to work but can't figure it out... Any help would be appreciated.
Thanks guys, you're the best :)
UPDATE:
Full functions are here:
$(document).ready(function() {
$(".startServer").click(function(){
$.post("controller.php",{server: this.name});
setTimeout("showStatus('"+this.name+"')", 3000);
});
$(".stopServer").click(function(){
$.post("controller.php",{stop: 'true', server: this.name});
setTimeout("showStatus('"+this.name+"')", 3000);
});
function showStatus(name) {
alert(name);
$('#test'+name).load('controller.php?status=true&server='+name);
}
});
UPDATE
Given up on the idea of it, instead the status is polled for every second instead.
var refreshId = setInterval(function()
{
$('.status').each(function() {
var $name = $(this).attr('name');
$(this).load("controller.php?status=true&server=" + $name);
});
}, 1000);
I've added a quick sample of wrapping the function in a setTimeout
$(document).ready(function(){
$('#test').click(function(){
var message = 'hello';
setTimeout(function(){ callback(message) },1000);
});
function callback(name){
alert(name);
}
});
JSFiddle DEMO
I dont know if you will get a response from 'controller.php' when the server actually shuts down, in case you don't, try this...
$(".stopServer").click(function(){
$.post("controller.php",{stop: 'true', server: this.name});
setTimeout("showStatus('"+this.name+"')", 10000);
});
function showStatus(name) {
$command = $('#test'+name).load('controller.php?status=true&server='+name);
}
ajax calls are asynchronous. the $.post() call returns immediately and lets the actual post work be done in the background. either change it to a synchronous call (usually not a good idea), or put the subsequent code in the "success" part of the .post call, e.g.
$.post('controller.php', success: function(data) {
$command = etc....
});
I've looked around a bit and haven't found an answer to this yet.
I have an ajax request that when you click the button it sends info to the server and hides the current div and loads a loading gif. I have it set so when the server responds it gets rid of loading gif and shows the content from the server.
code:
$("#submit").click(function(e){
e.preventDefault();
var $domain = $.fn.HTTP($('#domain').val());
if(!$.fn.ValidURL($domain)){
$('#domainerror').fadeIn(500);
return false;
}
if($('#domainerror').css('display')!=='none'){
$('#domainerror').fadeOut(350);
}
$('#question').hide(500, function(){
$('#waiting').show(350);
});
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
});
The problem is jQuery receives the response from the server too fast and the loading gif doesn't disappear.
However if I tell the server to sleep for 3 seconds it works just fine. This is not the solution I want.
Any ideas?
Surely it's a good thing your users aren't having to see a loading animation because it's so fast?!
Anyway, the problem is that the animation is taking at least 500ms - animations are processed asynchronously, at the same time as your AJAX request. Instead of making the server sleep, which is arguably a waste of CPU, make the browser wait instead, before you send the AJAX request.
Put the call in a setTimeout() function, this example will make it wait 3 seconds:
setTimeout(function() {
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
}, 3000);
The ideal solution however would be to not use animation effects and just use show() and hide().
Get rid of the delay in showing the waiting animation, so it's not still showing up when the request returned.
$('#question').hide() //was 500
$('#waiting').show(); //was 350
If you add all up that's almost a second later. By that time the ajax request may have returned in most systems, so it's not worth to be still animating by that point
Use Javascript's setTimeout. Code may look something (perhaps not exactly) like this:
setTimeout("getResponse()", 3000);
function getResponse() {
$.getJSON('http://localhost/file.php',
{
i: $domain
},
function(data){
$('#answer').html(data.message + $('#trybutton').html());
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
});
}
That way you've got your AJAX request still sending your i variable to the server, processing the code in file.php and sending back data which you can handle. The only trick is to put this in a function (not required, but it certainly makes the setTimeout function look prettier) and call it after 3000 milliseconds.
Seems like the ajax callback is executed before the question hiding ends, and the $('#waiting').show(350); comes after $('#waiting').hide(350, ...). You have three possibilities to solve that:
If you'd show the #waiting img immidiately (not waiting for the question to fade out), this won't happen; the answer should then also not wait for #waiting to hide.
Or you use a variable to indicate that the answer is already fading in when the question has faded out, and show no animation then:
var answered = false,
waiting = false;
$('#question').hide(500, function(){
if (!answered) {
waiting = true;
$('#waiting').show(350);
}
});
$.getJSON('http://localhost/file.php', {
i: $domain
}, function(data){
$('#answer').html(data.message + $('#trybutton').html());
answered = true;
if (waiting) {
$('#waiting').stop().hide(350, function(){
$('#answer').show(350);
});
} else {
$('#answer').show(350);
}
});
If you want the four animations to show always and consecutively (at least 1550ms), you'd need to code them manually:
var showanswer = false;
$('#question').hide(500, function() {
$('#waiting').show(350, function() {
if (showanswer) // already loaded
showanswer(); // execute callback
else
showanswer = true; // mark as shown
});
});
$.getJSON('http://localhost/file.php', {
i: $domain
}, function(data){
$('#answer').html(data.message + $('#trybutton').html());
function animate() {
$('#waiting').hide(350, function(){
$('#answer').show(350);
});
}
if (showanswer) // waiting image shown
animate();
else
showanswer = animate; // set as callback
});
A button click fires my function that fetches image data via an AJAX-call:
$("#toggle_album").click(function () {
album_id = $("#album_id").val();
$.post('backend/load_album_thumbnails.php', {
id: album_id
}, function(xml) {
var status = $(xml).find("status").text();
var timestamp = $(xml).find("time").text();
$("#album_thumbs_data_"+album_id+"").empty();
if (status == 1) {
var temp = '';
var output = '';
$(xml).find("image").each(function(){
var url = $(this).find("url").text();
temp = "<DIV ID=\"thumbnail_image\">[img-tag with class="faded" goes here]</DIV>";
output += temp;
});
$("#album_thumbs_data_"+album_id+"").append(output);
} else {
var reason = $(xml).find("reason").text();
var output = "<DIV CLASS=\"bread\">"+reason+"</DIV>";
$("#album_thumbs_data_"+album_id+"").append(output);
}
$("#album_thumbs_"+album_id+"").toggle();
});
});
The data is returned in XML format, and it parses well, appending the data to an empty container and showing it;
My problem is that my image overlay script:
$("img.faded").hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
});
... stops working on the image data that I fetch via the AJAX-call. It works well on all other images already loaded by "normal" means. Does the script need to be adjusted in some way to work on data added later?
I hope my question is clear enough.
Okay, apparantly I hadn't googled it enough. Surfing my own question here on stackoverflow pointed me to other questions, which pointed me to the JQuery live() function: live().
However, it does not work on hover(), so I rewrote the script to use mouseover() and mouseout() instead:
$("img.faded").live("mouseover",function() {
$(this).animate({"opacity": "1"}, "fast");
});
$("img.faded").live("mouseout", function() {
$(this).animate({"opacity": "0.5"}, "fast");
});
... and now it works flawlessly even on the content I fetch from the AJAX-call.
Sorry if anyone has started writing an answer already.
You have to bind the new events each time you add a DOM element to the page.
There is a built-in function in jquery called live that does that for you.
I noticed you add the images from your xml; you can add there the new binds too.
$(xml).find("image").each(function(){
//this actually creates a jquery element that you can work with
$('my-img-code-from-xml-goes-here').hover(
function() {
$(this).animate({"opacity": "1"}, "fast");
},
function() {
$(this).animate({"opacity": ".5"}, "fast");
}
//i did all my dirty stuff with it, let's add it where it belongs!
).appendTo($('some-already-created-element'));
});
EDIT: corrected a wrong sentence.