I am going to update a small chat between two users every minute. This is already working - however I can't figure how to do an AJAX call to update the DIV containing the actual messages.
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
function updateMessages() {
$(function () {
// UPDATE #mail_container
});
}
What´d be a proper way approaching this?
The easiest way is probably to include jQuery and make use of either its .append() or .html() methods.
eg. $("#mail_container").html("<p>Your chat message</p>");
See:
http://api.jquery.com/append/
http://api.jquery.com/html/
Related
I am building a chat. I have this Jquery working code which calls logs.php every second and refreshes the chat.
$(document).ready(
function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {
$('#chatlogs').load('logs.php');
updateScroll();
}, 1000);
}
);
As you can see, also updateScroll, a JS function on my page, gets called. Updatescroll creates a variable, which I would like to pass on to logs.php, is there any way to do this? In other words, updatescroll basically checks everysecond if the user has scrolled up to the top of the chat. If so, I am gonna tell logs.php to load -say - another 10 messages. But in order to do this, I have to have something that from updatescroll passes on to the Jquery function and thus onto logs.php. You get it? Thanks
First, when it comes to ajax, I would recommend using a window.setTimeout, intervals can get tricky when you are running things asynchronously (if one call hangs you can end up with multiple calls to the same script).
so something more like:
(function($){
var update_messages = function(){
var count = updateScroll();
$('#chatlogs').load('logs.php?count='+count, function(){
window.setTimeout(update_messages, 1000);
});
}
$(document).ready(function(){
$.ajaxSetup({cache:false});
update_messages();
});
})(jQuery);
Then in your PHP script the "count" would be available via $_GET['count'].
EDIT: you can see an anonymous function is being sent as a second argument to load, this will be called AFTER the AJAX call is complete, so we can make sure only 1 of these is running at a time
I've got a script in an HTML file that runs a php file every 30 seconds. The php file is intended to change a div's innerHTML. I don't seem to find the way to replace it.
I was using load() but there are several divs I want to keep updating every 30 seconds and I don't want to make the server GET that much requests. So I'm looking for one only php get and then change the innerhtml in those several divs
This is what i've got:
HTML:
<script type="text/javascript">
$(document).ready(function () {
$.get('php.php');
});
setInterval(function(){
$.get('php.php');
}, 30000);
</script>
<div id="foo"></div>
php.php:
document.getElementById("foo").innerHTML = '<?php
// some php code
?>';
I think the problem is I'm not being able to get the element from the parent HTML file. I don't know how to solve this...
Any suggestions will be more than aprecciated!
You are reinventing jQuery's load()
function fetchContent() {
$("#foo").load('php.php');
window.setTimeout(fetchContent, 30000);
}
$(fetchContent);
The server should just return the HTML content that you want to display.
EDIT
Since your comment is different from the original question.
function fetchContent() {
$("#foo").get('php.php', function(data) {
var html = $("<div/>").html(data);
$("#foo").html( html.find("#Section1").html() );
$("#bar").html( html.find("#Section2").html() );
$("#asd").html( html.find("#Section3").html() );
window.setTimeout(fetchContent, 30000);
});
}
$(fetchContent);
You would want to add an onError handler and might want to set the no cache option for the Ajax calls.
what you probably want is for your php.php to return some data, and then you use the success of the $.get to update your #foo; taking an example from http://api.jquery.com/jQuery.get/ and modifying it for your example
$.get("php.php", function( data ) {
$( '#foo' ).html( data );
});
hope that helps :)
I am programming an online PHP-based fantasy pet simulation game. I am not very familiar with AJAX, so please keep this in mind when answering.
On pet pages, I would like users to be able to feed/water/play with their pets without needing to reload the entire page - that's why I'm using AJAX. Here's what I have so far:
Working Script
$(function() {
$(".petcareFood").click(function(event) {
event.preventDefault();
$("#petcareFood").load($(this).attr("href"));
});
});
$(function() {
$(".petcareWater").click(function(event) {
event.preventDefault();
$("#petcareWater").load($(this).attr("href"));
});
});
$(function() {
$(".petcarePlay").click(function(event) {
event.preventDefault();
$("#petcarePlay").load($(this).attr("href"));
});
});
</script>
Working HTML
<a class=\"petcareFood\" href=\"petcare.php?pet=#&action=#\">Feed Your Pet</a>
<a class=\"petcareWater\" href=\"petcare.php?pet=#&action=#\">Water Your Pet</a>
<a class=\"petcarePlay\" href=\"petcare.php?pet=#&action=#\">Play With Your Pet</a>
NOW, everything that I listed above works like a charm! This is my problem: I want those links to also update another DIV - the one which contains updated status bars showing how hungry/thirsty/unhappy their pet is. Currently, I am doing that like this:
The Almost Working Script
$(function() {
$(".petcareFood").click(function(event) {
event.preventDefault();
$('#petcareHunger').load('ajax/hunger.php?pet=#');
});
});
$(function() {
$(".petcareWater").click(function(event) {
event.preventDefault();
$('#petcareThirst').load('ajax/thirst.php?pet=#');
});
});
$(function() {
$(".petcarePlay").click(function(event) {
event.preventDefault();
$('#petcareMood').load('ajax/mood.php?pet=#');
});
});
The script above makes it so that when a user clicks one of the HTML links, it updates two DIVS (one DIV containing the message displayed when a user feeds/waters/plays with their pet, and the other containing the status bar). Now... that seems all fine well and good, BUT... if both scripts update at exactly same time, then the PHP that handles the status bar is not updated - it's still retrieving old information.
My question to all of you is: Is there any way that I can delay running the second set of script (so that it will update after the PHP makes changes to MySQL)?
I tried inserting this before "the almost working script":
setTimeout(function() {
$('#petcareMood').load('ajax/mood.php?pet=#');
}, 2000);
However, it doesn't work. Well - it does, but just once. Users need to play with their pets at least 3 times a day to achieve 100% happiness, and so delaying the second DIV only once doesn't cut it for me. When I tried adding the same script multiple times, it just stopped working all together. What can I do?!
If you'd like to see screen shots of how things are working, please just ask. I will be happy to provide them upon request.
Thank you in advance!
Instead of a hardcoded delay time, you maybe could use the callback function of the first ajax action:
//trigger first ajax
$("#petcarePlay").load($(this).attr("href"), function(){
//trigger second ajax call, when first is completed
$('#petcareHunger').load('ajax/hunger.php?pet=#');
});
see http://api.jquery.com/load/
You could use the complete parameter to specify a callback function that gets executed when the request completes. Then from within the callback, execute another request which actually updates the divs.
Example:
$(".petcareWater").click(function(event) {
event.preventDefault();
$("#petcareWater").load($(this).attr("href"), function(response, status, xhr) {
// code here to make another request for stats
}
});
Alternatively, you could have the initial URLs return some JSON data that contain the updated stats so when a person does something to/with their pet, it returns all the stats so you can immediately update the div's all with one call rather than having to make a secondary call for the data.
I'm not sure, but i think the ajax constructor is better for your purpose http://api.jquery.com/jQuery.ajax/.
There you can set that the AJAX will be synchronous(It will wait to finish the AJAX callback )
Here is a few theory about it :)
http://javascript.about.com/od/ajax/a/ajaxasyn.htm
Instead of setTimeout, use setInterval. When it's no longer needed, you can kill it using clearInterval.
setInterval will execute a given function every n milliseconds.
$(document).ready(function(){
setInterval(function(){
$('.bopa').load('accounts.php');
},30000);
});
Hi guys! Me again. So I got back to this stuff and I realized that this is JQuery. It maybe possible for me to put a fade effect somewhere there. I just don't konw where. Is it actually possible if so please tell me where. The accounts php actualy contains something like
$command=mysql_query("SELECT * FROM pages order by rand() limit 1");
now it works every 3 seconds the content changes. I am trying it on text first so that it'd be easier. Later on I'm planning to do it on pictures.
You can add a callback function to the AJAX request you're making:
$('.bopa').load('accounts.php');
Could change to:
//start by fading-out the element(s)
$('.bopa').fadeOut(250, function () {
//continue by loading the new content now that the element(s) has/have faded-out
$(this).load('accounts.php', function () {
//now that the new content has loaded, fade the element(s) back in
$(this).fadeIn(250);
});
});
This also takes advantage of the callback functions for the jQuery animation functions used (.fadeIn()/.fadeOut()).
I am developing a web-page in PHP that needs following functionality:
1. When User click on "Say Thanks" it should be changed with "Done!".
2. At the same time I want to call an action in indexController.
3. At this time I want to show "loading...."
4. The current page has a lot of dynamic contents that should also not change.
Please suggest me what should I do to complete above tasks......
I figure you need an AJAX call. I usually do that for loading comments and such when you press "more". In my case, there's an empty div and an <a> tag with the link to the comments view (with a separate action, ofc). Then I use jQuery for the AJAX magic:
$(function() {
$("a.CommentsListBtn").click(function() {
var tmpHref = $(this).attr("href");
var tmpLayer = $(this).parent().children("div.CommentsList");
tmpLayer.load(tmpHref, function() {
tmpLayer.stop().slideDown("medium");
});
return false;
});
});
I hope this helps.
Learn to use JQuery, JQuery UI. It isn't that hard! What I think you need to learn is the following for your problem:
.click()
.html()
jQuery.get()