How to pass variable to php script from Jquery $(document).ready function - php

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

Related

Updating a DIV box from controller using AJAX in CodeIgniter

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/

Delay AJAX from loading?

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.

JQuery Additional Questions Fade Effect

$(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()).

Javascript variable not working in a different file

I have this script in index.php file:
<script type="text/javascript">
$(document).ready(function(){
$('#ads').load('output.php').fadeIn('slow');
});
</script>
And the output.php file contains a hidden input by which I pass a php variable and retrieve it succesfully:
<script type="text/javascript">
num = document.getElementById('number').value;
</script>
And if I put, say, an alert(num); in the output.php file, everything works. Though when I do the same in the index.php file, javascript doesn't seem to see that num variable.
Im just going to ges that you dont actually wait until the file is actually loaded before testing to access that variable
http://api.jquery.com/load/
the load method takes a completed callback that u can use like this
$(document).ready(function(){
$('#ads').load('output.php', function() {
alert(num);
}).fadeIn('slow');
});
but you should probably not solve your problem this way i sugest you call a function from your
loaded file instead of setting a variable
You can't access variables before you create them. In the code you provided the first time num is being assigned to is when the output.php file is loaded and parsed. Since jQuery's load function isn't blocking - that is, your browser will continue executing JS while the load function is doing its magic - you have no good way to know when num will be assigned to. It could be milliseconds, or it could be never if your webserver refuses to return the output of output.php for whatever reason.
In jQuery programming, using a callback function is common practice, although you can make it cleaner by passing it a function reference instead of an inline function:
$(document).ready(function(){
$('#ads').load('output.php', outputLoadCallback).fadeIn('slow');
});
function outputLoadCallback(response, status) {
console.log(num);
}
Maybe an even better way would be to include the logic you need to run in the callback function like so:
var num; // Make sure num is in the global scope
function outputLoadCallback(response, status) {
num = document.getElementById('number').value;
console.log(num);
}
If you're "not much of a pro", may I suggest jQuery in Action?

Jquery click link send information to php

I'm creating a system using jquery and php that pops up a small div when they get a private message on my website. The alert itself I have figured out, but I'm not sure how to gracefully cancel it.
I've made it so that clicking a link "[x]" hides the div, but how can I make the link send enough information to a php script to mark this alert as "read" in the database?
All the php script would need is the id of the alert in the database, but I've got no idea how to make it do that. There is also more than one notice displayed at a time, so I would need a way to have each link send the information necessary to the php script.
Here's the jquery that loads the div and the php that powers it.
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#mc').load('/lib/message_center.php').show("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<script type="text/javascript">
$(document).ready(function(){
$('.delete').live('click', function(){
$('#mc').hide('slow');
});
});
</script>
The easiest solution would be to set the message you are displaying to read at the moment you display it. That would not require any additional communication between the browser and the server, just do it at the end of your /lib/message_center.php script for the messages you are displaying at that moment.
Set the href attribute for your X produced by php like href="javascript:killbox(5);" and give your div a unique id (i.e.id="boxtokill5"). Then you could use something like this:
function killbox(id){
$("#boxtokill"+id).hide();
var packet = {};
packet.clickedlinkid = id;
$.get("destination.php",packet,function(data){
// data = Response (output) from script
});
}
The destination.php receives the ID by $_GET['clickedlink'].

Categories