Help with Ajax call and Update (Twitter/Facebook style)
8 posts
Page 1 of 1
OK so what i have here id a simple div that gets loaded @ runtime via an aJax() call.
Code: Select all
What i need is to have the #divTL to check the database for any new records compared to what is already being displayed and then just simply "append" or add the new data from the ajax() call or what ever i need to use.<script type="text/javascript">
$(document).ready(function() {
function ahah(url, target) {
document.getElementById(target).innerHTML = '<div style="margin:50 auto;height:32px;text-align:center;background-image:url(TimeLine/img/Scottie1972.bmp);background-repeat:no-repeat;background-position:38.5% 0%;padding:8px;"> <img src="TimeLine/smiles/106.gif" title=""/>Fetching Public TimeLine... </div>';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
//Set Interval for Refresh
setInterval(function() {
load('TimeLine.php?timeline=public','divTL');
}, 60000)
// Loads result into #divTL
load('TimeLine.php?timeline=public','divTL');
});
TimeLine.php
Code: Select all
as you can see the mysql query in a <li></li> tag from the "formatTweet()" function in the ( functions.php ) file.<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" type="text/css" href="TimeLine/demo.css" />
<script type="text/javascript" src="TimeLine/script.js"></script>
<?php
define('INCLUDE_CHECK',1);
require "TimeLine/functions.php";
/* Database config */
$db_host = 'localhost';
$db_user = ' ';
$db_pass = ' ';
$db_database = 'website_database';
/* End config */
$link = mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_select_db($db_database,$link);
mysql_query("SET names UTF8");
//fetch the timeline
$q = mysql_query("SELECT * FROM demo_twitter_timeline ORDER BY ID DESC LIMIT 5");
$timeline='';
while($row=mysql_fetch_assoc($q)) {
$timeline.=formatTweet($row['id'],$row['avatar'],$row['name'],$row['tweet'],$row['dt']);
}
$tl = $_GET['timeline'];
switch($tl) {
case "public":
echo "<div id='twitter-container'>";
echo "<ul id='statuses' class='statuses'>";
echo $timeline;
echo "</ul>";//".$timeline."
echo "</div>";
break;
case "member":
$member = $_GET['member'];
break;
default:
echo "...there was an error...";
die();
}
?>
all this function really does in place the query data in a <li></li> tag and then it gets added to the <ul></ul> parent tag.
Code: Select all
function formatTweet($id,$avatar,$name,$tweet,$dt) {
if(is_string($dt)) $dt=strtotime($dt);
$tweet=htmlspecialchars(stripslashes($tweet));
$replacements = array(
"thumbsup;" => "<img src='TimeLine/smiles/thumbsup.png' width='18' height='18' title='Thumbs Up'/>",
"idk;" => "<img src='TimeLine/smiles/106.gif' title='I dont know!'/>",
"notlisten;" => "<img src='TimeLine/smiles/107.gif' title='Not Listening'/>",
"rofl;" => "<img src='TimeLine/smiles/24.gif' title='Rolling on floor lauching'/>"
);
$tweet = str_replace(array_keys($replacements), $replacements, $tweet);
//$arr = array('avatar' => $avatar, 'name' => $name, 'tweet' => $tweet, 'dt' => $dt);
if($name == "System") {
return '
<li id="tweetSystem">
<a href="#"><img class="avatar" src="images/avatar/default_avatar.png" width="24" height="24" alt="avatar" /></a>
<div class="tweetTxt">
<strong><a href="javascript:void(System);">'.$name.' Report</a>:</strong>[ '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?[^\s\"\']+)/i','<a href="$1" rel="nofollow" target="blank">'.TinyURL('.$1.').'</a>','<font color=#99CCFF>'.$tweet.'</font> ]').'
<div class="date">'.relativeTime($dt).'</div>
</div>
<div class="clear"></div>
</li>';
} else {
return '
<li id="tweet'.$id.'">
<a href="#"><img class="avatar" src="'.$avatar.'" width="24" height="24" alt="avatar" /></a>
<div class="tweetTxt">
<strong><a href="javascript:void('.$name.');">'.$name.'</a> said: </strong> '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?[^\s\"\']+)/i','<a href="$1" rel="nofollow" target="blank">'.TinyURL('.$1.').'</a>',$tweet).'
<div class="date">'.relativeTime($dt).'</div>
</div>
<div class="clear"></div>
</li>';
}
}
functions.php
Code: Select all
script.js
<?php
if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this file directly');
function relativeTime($dt,$precision=2) {
$times=array( 365*24*60*60 => "year",
30*24*60*60 => "month",
7*24*60*60 => "week",
24*60*60 => "day",
60*60 => "hour",
60 => "minute",
1 => "second");
$passed=time()-$dt;
if($passed<5) {
$output='less than 5 seconds ago';
}
else
{
$output=array();
$exit=0;
foreach($times as $period=>$name)
{
if($exit>=$precision || ($exit>0 && $period<60)) break;
$result = floor($passed/$period);
if($result>0)
{
$output[]=$result.' '.$name.($result==1?'':'s');
$passed-=$result*$period;
$exit++;
}
else if($exit>0) $exit++;
}
$output=implode(' and ',$output).' ago';
}
return $output;
}
function formatTweet($id,$avatar,$name,$tweet,$dt) {
if(is_string($dt)) $dt=strtotime($dt);
$tweet=htmlspecialchars(stripslashes($tweet));
$replacements = array(
"thumbsup;" => "<img src='TimeLine/smiles/thumbsup.png' width='18' height='18' title='Thumbs Up'/>",
"idk;" => "<img src='TimeLine/smiles/106.gif' title='I dont know!'/>",
"notlisten;" => "<img src='TimeLine/smiles/107.gif' title='Not Listening'/>",
"rofl;" => "<img src='TimeLine/smiles/24.gif' title='Rolling on floor lauching'/>"
);
$tweet = str_replace(array_keys($replacements), $replacements, $tweet);
//$arr = array('avatar' => $avatar, 'name' => $name, 'tweet' => $tweet, 'dt' => $dt);
//$arr["avatar"]
//$arr["name"]
//$arr["tweet"]
//$arr["dt"]
if($name == "System") {
return '
<li id="tweetSystem">
<a href="#"><img class="avatar" src="images/avatar/default_avatar.png" width="24" height="24" alt="avatar" /></a>
<div class="tweetTxt">
<strong><a href="javascript:void(System);">'.$name.' Report</a>:</strong>[ '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?[^\s\"\']+)/i','<a href="$1" rel="nofollow" target="blank">'.TinyURL('.$1.').'</a>','<font color=#99CCFF>'.$tweet.'</font> ]').'
<div class="date">'.relativeTime($dt).'</div>
</div>
<div class="clear"></div>
</li>';
} else {
return '
<li id="tweet'.$id.'">
<a href="#"><img class="avatar" src="'.$avatar.'" width="24" height="24" alt="avatar" /></a>
<div class="tweetTxt">
<strong><a href="javascript:void('.$name.');">'.$name.'</a> said: </strong> '. preg_replace('/((?:http|https|ftp):\/\/(?:[A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?[^\s\"\']+)/i','<a href="$1" rel="nofollow" target="blank">'.TinyURL('.$1.').'</a>',$tweet).'
<div class="date">'.relativeTime($dt).'</div>
</div>
<div class="clear"></div>
</li>';
}
}
function TinyURL($u){
return file_get_contents('http://tinyurl.com/api-create.php?url='.$u);
}
?>
Code: Select all
submit.php
$(document).ready(function(){
$('#inputField').bind("blur focus keydown keypress keyup", function(){recount();});
$('input.submitButton').attr('disabled','disabled');
$('#tweetForm').submit(function(e){
tweet();
e.preventDefault();
});
});
function recount()
{
var maxlen=140;
var current = maxlen-$('#inputField').val().length;
$('.counter').html(current);
if(current<0 || current==maxlen)
{
$('.counter').css('color','#D40D12');
$('input.submitButton').attr('disabled','disabled').addClass('inact');
}
else
$('input.submitButton').removeAttr('disabled').removeClass('inact');
if(current<10)
$('.counter').css('color','#D40D12');
else if(current<20)
$('.counter').css('color','#5C0002');
else
$('.counter').css('color','#cccccc');
}
function tweet()
{
var submitData = $('#tweetForm').serialize();
$('.counter').html('<img src="TimeLine/img/ajax_load.gif" width="16" height="16" style="padding:12px" alt="loading" />');
$.ajax({
type: "POST",
url: "submit.php",
data: submitData,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('ul.statuses li:first-child').before(msg);
$("ul.statuses:empty").append(msg);
//$('#lastTweet').html($('#inputField').val());
$('#inputField').val('');
recount();
}
}
});
}
Code: Select all
<?php
define('INCLUDE_CHECK',1);
require "functions.php";
require "connect.php";
if(ini_get('magic_quotes_gpc'))
$_POST['inputName'] = stripslashes($_POST['inputName']);
$_POST['inputField'] = stripslashes($_POST['inputField']);
$_POST['inputName'] = mysql_real_escape_string(strip_tags($_POST['inputName']),$link);
$_POST['inputField'] = mysql_real_escape_string(strip_tags($_POST['inputField']),$link);
if(mb_strlen($_POST['inputField']) < 1 || mb_strlen($_POST['inputField'])>140) die("0");
mysql_query("INSERT INTO demo_twitter_timeline SET avatar='".$_POST['avatar']."',name='".$_POST['inputName']."',tweet='".$_POST['inputField']."',dt=NOW()");
//mysql_query("INSERT INTO demo_twitter_timeline (avatar, name, tweet, dt) VALUES (".$avatar22.", ".$_POST['inputName'].", ".$_POST['inputField'].", ".NOW().") ");
if(mysql_affected_rows($link)!=1) die("0");
echo formatTweet($_POST['inputField'],time());
?>
Now!
does anyone have any ideas on how i can achieve the effect that i would like?
This might help you - http://www.dzyngiri.com/?p=558
Instead of LOL use this -
LSIBMHBIWFETALOL
Which means -
Laughing silently in between my head because it wasn't funny enough to actually laugh out loud!
LSIBMHBIWFETALOL
Which means -
Laughing silently in between my head because it wasn't funny enough to actually laugh out loud!
You know im not very good with ajax and php and im not sure I can help with the appending part but looking at the mchat we use here it gives each message a unique ID number (auto incrementing in the database).
So when chat loads for the first time it gets all messages from the database and displays them and stores the last message ID into a variable. Then in the ajax code that runs every X seconds after the page has first loaded it passes that variable into the ajax call url something like:
GetNewMessages.php?id=lastmessageID
Then the mysql code gets a all messages where the message ID is higher than last message ID like:
WHERE MessID > id
Then it would get the last message id from the database and store it again for next ajax call.
Atleast that looks like how it works lol. Make sense :?
So when chat loads for the first time it gets all messages from the database and displays them and stores the last message ID into a variable. Then in the ajax code that runs every X seconds after the page has first loaded it passes that variable into the ajax call url something like:
GetNewMessages.php?id=lastmessageID
Then the mysql code gets a all messages where the message ID is higher than last message ID like:
WHERE MessID > id
Then it would get the last message id from the database and store it again for next ajax call.
Atleast that looks like how it works lol. Make sense :?
Welcome to CodenStuff.com Learn Code, Love Code. Thank you for being a member of the community.
CodenStuff wrote:You know im not very good with ajax and php and im not sure I can help with the appending part but looking at the mchat we use here it gives each message a unique ID number (auto incrementing in the database).this is the part that i am missing!
So when chat loads for the first time it gets all messages from the database and displays them and stores the last message ID into a variable. Then in the ajax code that runs every X seconds after the page has first loaded it passes that variable into the ajax call url something like:
GetNewMessages.php?id=lastmessageID
Then the mysql code gets a all messages where the message ID is higher than last message ID like:
WHERE MessID > id
Then it would get the last message id from the database and store it again for next ajax call.
Atleast that looks like how it works lol. Make sense :?
my code is incomplete and even maybe way off from what i really need it to be.
im not sure. i always run into this same problem everytime i create a web app like this one.
Can you package up and send me all the files for this and ill have a play with it and see if I can get it to work.
Welcome to CodenStuff.com Learn Code, Love Code. Thank you for being a member of the community.
You can just go to phpmyadmin and go to the field structure and press the autoincrement. Then in your php where you make the mysql call, use $_GET["lastmsg"]; or similar to get the id passed from the url.
We shall let the revolution begin.. the revolution for freedom, freedom against censorship. We shall fight in the fields and in the streets, we shall fight in the hills; we shall never surrender
CodenStuff wrote:Can you package up and send me all the files for this and ill have a play with it and see if I can get it to work.yeah give me a few days. it is part of a template system and i dont have alot of computer time this week.
8 posts
Page 1 of 1
Copyright Information
Copyright © Codenstuff.com 2020 - 2023