Page 1 of 1

AJAX: I built something, but i dont know how it works!!

Posted: Wed Aug 16, 2006 10:07 am
by JayBird
This is a bit of a weird one. I was just messing around with AJAX to build something similar to DiggSpy

Anyway, it is a combination of code i have written and code i grabbed from various sources.

Basically, using AJAX, i query the database every 10 seconds to see if there is a new "action" in the database. This is then output to the screen.

...but, what i dont understand is, if after the 10 seconds has elapsed there isn't a new action, why it doesn't display the action it displayed 10 seconds ago becuase i didn't build anything into this to stop it.

Dont get me wrong, the way it is working is the intended way, but i just dont know how it does it.

Anyway, here is the code if someone could enlighten me

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript"
  src="latest.js"></script>
<script type="text/javascript" src="spy.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready(function() { 
		$('#spyContainer').spy({ limit: 10, fadeLast: 5, ajax: 'out.php', timeout: 2000,
		push : function(r) { $('#' + this.id).prepend(r); }});
	});
</script>
</head>

<body>
<div id="spyContainer"><div>
</body>
</html>
spy.js

Code: Select all

/*
	jQuery Plugin spy (leftlogic.com/info/articles/jquery_spy)
	(c) 2006 Remy Sharp (leftlogic.com) jquery[at]leftlogic[dot]com
	$Id: spy.js,v 1.2 2006/08/14 10:07:18 remy Exp $
*/
var spyRunning = 1;

$.fn.spy = function(settings) {
	if (!settings['ajax'])
	{
		alert("An AJAX/AJAH URL must be set for the spy to work.");
		return;
	}
	
	var o = {
		limit: (settings['limit'] || 10),
		fadeLast: (settings['fadeLast'] || 5),
		ajax: settings['ajax'],
		timeout: (settings['timeout'] || 3000),
		push: (settings['push'] || -1),
		fadeInSpeed: (settings['fadeInSpeed'] || 'slow')
	};
	
	return this.each(function() {
		var e = this;
		var lr = '';
		var epoch = new Date(1970, 1, 1);
	    var now = new Date();
	    var timestamp = Math.floor((now - epoch) / 1000);
		e.timer = window.setInterval(function() {
			if (spyRunning)
			{
				$.post(o['ajax'], { 'timestamp': timestamp }, function(r) {
					if (r != lr) // don't show dupes
					{
						$('#' + e.id + ' > div:gt(' + (o['limit'] - 2) + ')').remove();
						$('#' + e.id + ' > div:gt(' + (o['limit'] - o['fadeLast'] - 2) + ')').fadeEachDown();
						if (o['push'] == -1)
							$('#' + e.id).prepend(r);
						else
							o['push'].call(e, r);
						$('#' + e.id + ' > div:first').fadeIn(o['fadeInSpeed']);
						lr = r;					
					}
				});
				now = new Date();
			    timestamp = Math.floor((now - epoch) / 1000);
			}
		}, o['timeout']);
	});
};

$.fn.fadeEachDown = function() {
	var s = this.size();
	return this.each(function(i) {
		var o = 1 - (s == 1 ? 0.5 : 0.85/s*(i+1));
		var e = this.style;
		if (window.ActiveXObject)
			e.filter = "alpha(opacity=" + o*100 + ")";
		e.opacity = o;
	});
};

function pauseSpy() {
	spyRunning = 0; return false;
}

function playSpy() {
	spyRunning = 1; return false;
}
out.php

Code: Select all

<?php
require("../../includes/generic/config.inc.php");
require("../../includes/generic/database.class.php");

$db = new db($dbhost, $dbname, $dbuser, $dbpass);

$sql = "SELECT * FROM `spy` ORDER BY `id` DESC LIMIT 1";

$result = $db->query($sql);

$line = $db->fetchArray($result, "MYSQL_ASSOC");

echo '<div class="jobList">';
echo '<div class="listItem">';
echo '<h3><a href="#">'.$line['action'].'</a></h3>';
echo '<p><strong>User IP:</strong>'.$line['userIP'].' <strong>Time:</strong> '.date("d/m/Y h:i:s A", $line['timestamp']).'</p>';
echo '</div>';
echo '</div>';
?>

Posted: Wed Aug 16, 2006 8:24 pm
by matt1019
Okay ajax gurus,

Time to shine your badges ;)

-Matt

Posted: Wed Aug 16, 2006 10:28 pm
by nickvd
The Spy Plugin takes care of it for you...

Code: Select all

if (r != lr) // don't show dupes
if the current block does not equal the last block then......

Posted: Thu Aug 17, 2006 2:55 am
by JayBird
nickvd wrote:The Spy Plugin takes care of it for you...

Code: Select all

if (r != lr) // don't show dupes
if the current block does not equal the last block then......
Well spotted...i actually knew that, but wanted to see if anyone else spotted it Image

Posted: Thu Aug 17, 2006 7:06 am
by christian_phpbeginner
Well, since the discussion has ended, I hope you guys won't mind if I ask something a little bit out of topic.

Since you're talking about AJAX....Do you guys have any good links or references to learn AJAX ? I've looked in the Useful Resources Sticky, but can't find one.

I have visited the http://www.w3schools.com, but I don't think it's enough.

Thank you so much.

Chris

Posted: Thu Aug 17, 2006 7:35 am
by bmcewan
christian_phpbeginner wrote:Well, since the discussion has ended, I hope you guys won't mind if I ask something a little bit out of topic.

Since you're talking about AJAX....Do you guys have any good links or references to learn AJAX ? I've looked in the Useful Resources Sticky, but can't find one.

I have visited the http://www.w3schools.com, but I don't think it's enough.

Thank you so much.

Chris
This might be a start,

http://www.dynamicdrive.com/dynamicinde ... ontent.htm

have a play with that and you can see how it works.

Also,

http://www.google.co.uk/search?hl=en&q= ... gle+Search

Posted: Thu Aug 17, 2006 10:47 am
by matt1019
JayBird wrote:
nickvd wrote:The Spy Plugin takes care of it for you...

Code: Select all

if (r != lr) // don't show dupes
if the current block does not equal the last block then......
Well spotted...i actually knew that, but wanted to see if anyone else spotted it Image
Ahhh.. I see, so this was kind of a trick question on your part? :)

one of these days... when I will be "fluent" in AJAX, i will be able to spot subtle changes/differences.

-Matt

Posted: Thu Aug 17, 2006 2:29 pm
by christian_phpbeginner
bmcewan wrote: This might be a start,

http://www.dynamicdrive.com/dynamicinde ... ontent.htm

have a play with that and you can see how it works.

Also,

http://www.google.co.uk/search?hl=en&q= ... gle+Search
Hello ! Thanks a lot. I am visiting the link you gave me now, and It's great. It's funny because I've searched for ajax tutorials using http://www.google.com, but instead google.co.uk gives more results. Next time, I'll try to search both the .com and also in the .co.uk.

Once again, thanks !

Chris

Posted: Wed Aug 23, 2006 8:47 pm
by matt1019
@JayBird

NOPE, dosen't quite work with me....

Displays the first record, and then hangs ;(

i checked several times to see I had more than 1 record.... I do.

Any suggestions anyone?

thanks.

-Matt

Posted: Thu Aug 24, 2006 3:03 am
by JayBird
@matt1019: Show your code

Posted: Thu Aug 24, 2006 10:32 am
by matt1019
@JayBird:

ieee... sorry.


Here's How Mine is setup:

I have a folder called "spy" and it has 4 files:

spy.js
jquery.js
index.php
out.php


Here's the code for spy.js

Code: Select all

/*
        jQuery Plugin spy (leftlogic.com/info/articles/jquery_spy)
        (c) 2006 Remy Sharp (leftlogic.com) jquery[at]leftlogic[dot]com
        $Id: spy.js,v 1.2 2006/08/14 10:07:18 remy Exp $
*/
var spyRunning = 1;

$.fn.spy = function(settings) {
        if (!settings['ajax'])
        {
                alert("An AJAX/AJAH URL must be set for the spy to work.");
                return;
        }
       
        var o = {
                limit: (settings['limit'] || 10),
                fadeLast: (settings['fadeLast'] || 5),
                ajax: settings['ajax'],
                timeout: (settings['timeout'] || 3000),
                push: (settings['push'] || -1),
                fadeInSpeed: (settings['fadeInSpeed'] || 'slow')
        };
       
        return this.each(function() {
                var e = this;
                var lr = '';
                var epoch = new Date(1970, 1, 1);
            var now = new Date();
            var timestamp = Math.floor((now - epoch) / 1000);
                e.timer = window.setInterval(function() {
                        if (spyRunning)
                        {
                                $.post(o['ajax'], { 'timestamp': timestamp }, function(r) {
                                        if (r != lr) // don't show dupes
                                        {
                                                $('#' + e.id + ' > div:gt(' + (o['limit'] - 2) + ')').remove();
                                                $('#' + e.id + ' > div:gt(' + (o['limit'] - o['fadeLast'] - 2) + ')').fadeEachDown();
                                                if (o['push'] == -1)
                                                        $('#' + e.id).prepend(r);
                                                else
                                                        o['push'].call(e, r);
                                                $('#' + e.id + ' > div:first').fadeIn(o['fadeInSpeed']);
                                                lr = r;     
                                        }
                                });
                                now = new Date();
                            timestamp = Math.floor((now - epoch) / 1000);
                        }
                }, o['timeout']);
        });
};

$.fn.fadeEachDown = function() {
        var s = this.size();
        return this.each(function(i) {
                var o = 1 - (s == 1 ? 0.5 : 0.85/s*(i+1));
                var e = this.style;
                if (window.ActiveXObject)
                        e.filter = "alpha(opacity=" + o*100 + ")";
                e.opacity = o;
        });
};

function pauseSpy() {
        spyRunning = 0; return false;
}

function playSpy() {
        spyRunning = 1; return false;
}
here's the code for jquery.js

umm never mind about the jquery.js.... I think its' obfuscated/ and or encoded. but its available straight from http://jquery.com/

here's the code for index.php

Code: Select all

<?php
error_reporting(E_ALL);
include "../../../maincore.php";
include BASEDIR."subheader.php";
include BASEDIR."side_left.php";

echo "<script type=\"text/javascript\" src=\"jquery.js\"></script>
	<script type=\"text/javascript\" src=\"spy.js\"></script>
	<script type=\"text/javascript\" charset=\"utf-8\">
      	$(document).ready(function() {
			$('#spyContainer').spy({ limit: 100, fadeLast: 5, ajax: 'out.php', timeout: 2000,
			push : function(r) { $('#' + this.id).prepend(r); }});
        	});
	</script>";

echo "<div id=\"spyContainer\"><div>";
?>
I tried to close the div tag (second to last line), but that didnt work either

here's the code for out.php

Code: Select all

<?php
error_reporting(E_ALL);
include "../../../maincore.php";

$getspy = dbquery("SELECT * FROM ".$db_prefix."user_activities ORDER BY id DESC LIMIT 1");

$line = dbarray($getspy);

echo '<div class="jobList">';
echo '<div class="listItem">';
echo '<h3><a href="#">'.$line['activity_name'].'</a></h3>';
echo '<p><strong>User:</strong>'.$line['activity_performer'].' <strong>Time:</strong> '.$line['activity_time'].'</p>';
echo '</div>';
echo '</div>';
echo '<br>';
?>
I added the <br> tag... to see if that would help (incase the "new" feed from out.php overlapped... it didn't help.

Thanks JayBird.

-Matt

Posted: Thu Aug 24, 2006 10:41 am
by matt1019
like I said, it does work.... but only for the first record. After that, the script "HANGS" (does not pull any more records out of the DB.)

I checked to see if I had dupe record... i don't.

I mean, activity might be the same... but the users are different. same goes for the IP (it's the same, since i am testing this on my dev machine... not hosted on the internet)

-Matt

jquery spy no longer responding might be this...

Posted: Sat Aug 26, 2006 4:40 pm
by remy.sharp
Hi there,

I wrote the spy.js code last week - and though I'm about to release an upgrade, I thought I might be able to help you with your problem.

The problem, I'm fairly sure is the trailing <br /> at the end of your code. The logic in the spy is doing some counting that might put it off.

The other thing to do is add an explicit style on the container div (something I've fix/changed in the upcoming version).

Also - you don't need the custom push (push : function(r) { $('#' + this.id).prepend(r);} ), as you're doing the exact same thing as the spy.js code is doing so it's redundant.

I've changed the code below:

Hope this helps.

Regards,

Remy.

Code: Select all

<?php
error_reporting(E_ALL);
include "../../../maincore.php";

$getspy = dbquery("SELECT * FROM ".$db_prefix."user_activities ORDER BY id DESC LIMIT 1");

$line = dbarray($getspy);

echo '<div style="display: none;" class="jobList">';
echo '<div class="listItem">';
echo '<h3><a href="#">'.$line['activity_name'].'</a></h3>';
echo '<p><strong>User:</strong>'.$line['activity_performer'].' <strong>Time:</strong> '.$line['activity_time'].'</p>';
echo '</div>';
echo '</div>';
?>