I would like to be able to record the amount of seconds a person is on my site in the simplest way possible. Don't need google analytics or any other 3rd party sources.
The php script would create a connection to mysql and update the relevant values,
I found some script online, but it doesn't seem to be working:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<script>
$(document).ready(function()
{
var refreshId = setInterval(function()
$.load('timeonpage.php?wzx=<?php echo $t; ?>&ip=<?php echo $ip; ?>');
}, 5000);
);
</script>
Thanks for any help!
There is a syntax error, your missing an opening to the setInterval function, and the closing of the .ready method
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
var refreshId = setInterval(function(){ //SYNTAX ERROR HERE
$.load('timeonpage.php?wzx=<?php echo $t; ?>&ip=<?php echo $ip; ?>');
}, 5000);
}); // SYNTAX ERROR HERE
</script>
Additionally, I would recommend using the $.get method, as .load in JQuery is typically meant for loading HTML into a particular container:
var refreshId = setInterval(function(){
$.get('timeonpage.php',{wzx:<?php echo $t?>,ip:<?php echo $ip?>});
},5000);
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> </script>
<script>
$(document).ready(function()
{
var refreshId = setInterval(function(){ //ANOTHER ERROR
$.load('timeonpage.php?wzx=<?php echo $t; ?>&ip=<?php echo $ip; ?>');
}, 5000);
}); //ERROR ON THIS LINE
</script>
Well you're missing a '}' in there on the closing of document ready. Try that, might be something so simple, report back if it's not and will have another look at it :)
Also: If you'd consider a 3rd party service, take a look at GoSquared, seriously amazing site there :)
Edit: Another error on setInterval line :)
With your current method, a user might be counted as online for all 86,400 seconds in a day if they just leave their browser window open.
Personally, my site is set up such that every time a user actually loads a page, their "last page loaded" time is updated. Then, a cron script runs every minute and checks to see which users have loaded a page in that last minute. Counting those up allows me to determine reasonably well how much time each user has spent online.
Additionally, this would cause WAY less load on your server - your solution would probably kill it if you had more than 50 or so users on your site.
it would probably be a lot more efficient onLoad to call an Ajax script that saves the page and any other data you want to the database and then returns a unique id which you store in a variable. On the onbeforeunload event you could then make another call to the database with the unique id. Just my two cents...
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
This would be a common question but what I'm looking for is:
My PHP Script does:
Read a remote page using cURL
Update every 20 Seconds
I want to auto update a div(Not whole page), (Which is populated using cURL) every 20 seconds.
I've read many solutions but that doesn't show updated data in source code (Crawl-able form).
Pls suggest me a solution how to update a div with cURL updated data, and that should populate/include in my page's source code.
Let me know if anything is unclear. sorry for bad english :(
Copy your cURL PHP codes into a new file named "reloader.php", in your main page, also put the source codes which reads the data(cURL stuff) in a div "id = to_be_reloaded", in your main page add these:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#to_be_reloaded').load('reloader.php').fadeIn("slow");
}, 20000); // refresh every 20000 milliseconds(20 seconds)
</script>
I know you need it for commenting system and
The workaround is use setInterval like this:
<script type="text/javascript">
setInterval(function(){
$.ajax({
url:'PUT YOUR URL',
success:function(data){
$('#comment').append($(data).fadeIn());
}
});
}, 20000);
</script>
Anything else ...
good luck
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.
I've got a div that randomly shows 1 of 10 files on each pageload. I'd like this to reload on a set time interval of 8 seconds, giving me a different one of the 10 files each reload.
I've read a few of the related questions using jQuery .load as a solution but this doesn't quite work with my code since I'm not loading a specific file each time.
This is my div content:
<div id="tall-content">
<?
$random = rand(1,10);
include 'tall-files/' . $random . '.php';
?>
</div>
Thanks
Using only PHP to accomplish this is impractical. This example uses jQuery and PHP.
$(document).ready(function() {
$("#div").load("random.php");
var refreshId = setInterval(function() {
$("#div").load('random.php');
}, 8000);
$.ajaxSetup({ cache: false });
});
random.php
$pages = array("page1.php", "page2.php", "page3.php", "page4.php", "page5.php");
$randompage = $pages[mt_rand(0, count($pages) -1)];
include ($randompage);
while using PHP to generate the random content, you cannot get the div to reload that content without refreshing the entire page.
A better solution is to use AJAX. You can store that PHP code that's inside the div container as a seperate file, and use ajax to request that php file. You can also set an infinite loop to request the php file every 8 seconds. Here is a sample, but you will need to re-code it to your specification:
<script language="javascript" type="text/javascript">
<!--
function ajaxFunction(){
var ajaxRequest;
try{ajaxRequest = new XMLHttpRequest();} catch (e){try{ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try{ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Browser/Settings conflict");return false;}}}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('tall-content').innerHTML = ajaxRequest.responseText;
}
}
var url = "random.php";
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
//-->
</script>
The only missing part is the refresh timer, since I do not program a lot in javascript I can't help you there. But the goal in this case is to create a file "random.php", put the random generator there, and use this script above to make an ajax request to random.php, which will place the output of that php script in the div container with the id of "tall-content". So really, you need to create another javascript which loops indefinitely calling the function "ajaxFunction()" and wait 8000 milliseconds .
If you want to do this while the user is sitting back in the chair on your page, the answer is javascript.
You could use this function for example.
function recrusive_timeout_function() {
setTimeout(function() {
recrusive_timeout_function();
}, 8000);
}
If you want to include a php file in that div (which outputs some html). Ajax is your friend and JQuery as a user friendly and easy to use javascript framework which handles your thinks really nice.
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'].