...

View Full Version : How to update comment count?



student101
12-22-2008, 05:36 PM
How would I update the count or comment count after doing an insert?
I have a working system but can't ever update the comment count without refreshing the entire page.

Is there a trick in getting the data from the db?

One other method is to add an extra column, updating the count each time a comment gets added, this would mean that I need to add my own auto-inc. values.

student101
12-23-2008, 09:38 AM
Just out of curiosity this can't be done without a page refresh?
Update a div after posting your comment?
If this is the case, I see no point in bothering with AJAX when I can do it the normal way.

ohgod
12-23-2008, 03:56 PM
wait... what now?

of course you can update a div with the return from an ajax request...

student101
12-23-2008, 05:39 PM
wait... what now?
of course you can update a div with the return from an ajax request...
Please show me how? If you need my code let me know.
Code added;


<!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=utf-8" />
<title>AJAX insert with no DIV refresh</title>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<?php $time = date("D, jS \of M Y");?>
</head>
<body>
<div class="container">
<form id="submit" method="post">
<p>
Name:<input id="name" value="">
<br>
Comment:<textarea cols="40" rows="3" id="comment"></textarea><br>
<input type="text" id="id" value="<?php echo $_GET['id']; ?>" size="2">
<input type="text" id="dateadded" value="<?php echo $time;?>" size="5">
<input name="submit" type="submit" class="button" value="Add Comment">
<input name="reset" type="reset" class="button" onclick="javascript:toggleLayer('commentForm');" value="Cancel">
</p>
</form>

<div class="success" style="display:none;">Comment added (comment count needs to update here...)</div>

</div>
<script type="text/javascript">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var name = $('#name').attr('value');
var comment = $('#comment').attr('value');
var id = $('#id').attr('value');
var dateadded = $('#dateadded').attr('value');

$.ajax({
type: "POST",
url: "ajax.php",
data: "name="+ name + "&" + "comment=" + comment + "&" + "id=" + id + "&" + "dateadded=" + dateadded,
success: function(del){
$('form#submit').hide();
$('div.success').fadeIn();
}
});
return false;
});
});
</script>
</body>
</html>

ajax.php only does the insert to db

Cheers

itsallkizza
12-23-2008, 05:44 PM
Ya, your code would be nice.

In specific, the ajax request handler function and the div you want updated.

EDIT: Just realized you might not have created any ajax yet, in which case you need to tell us what server-side script you have available for communicating with your database (hoping for ASP or PHP with MySQL).

student101
12-23-2008, 05:45 PM
Just added it above.

PHP with MySQL
Here is ajax.php below;


<?php
$con = mysql_connect("localhost","user","pass");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$comment= htmlspecialchars(trim($_POST['comment']));
$id= htmlspecialchars(trim($_POST['id']));
$sql="INSERT INTO comments (comments, id) VALUES ('$comment','$id')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());}
echo "Thank You";
mysql_close($con)
?>

Currently after $('div.success').fadeIn(); I've added to reload the page window.location.reload()
Forgot to add the comment count method. Sorry!


<?php
$sql = "SELECT COUNT(*) AS count FROM comments WHERE id = '$_GET[id]'";
$result = mysql_query($sql);
if($result){
$row = mysql_fetch_row($result);
$count = $row[0];
echo $count;
} else{
echo "Err";
}
?>

student101
12-23-2008, 07:14 PM
Ya, your code would be nice.
In specific, the ajax request handler function and the div you want updated.
Will that do?

itsallkizza
12-23-2008, 07:35 PM
I honestly don't have any experience with jQuery (I build all my frameworks myself). But judging from the code you posted, you should be able to do something like this:


function updateCount()
{
$.ajax({
type:"GET",
url:"get_count.php",
success:function(response){
document.getElementById("count").innerHTML = response.responseText;
}
});
}


You can then call updateCount in your JS during runtime and it will update your comment counter. In particular, you'll want to call that function right after someone adds a comment. So place it somewhere like this:


<!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=utf-8" />
<title>AJAX insert with no DIV refresh</title>
<script type="text/javascript" src="jquery-1.2.6.js"></script>
<script type="text/javascript">
// <![CDATA[
function updateCount()
{
$.ajax({
type:"GET",
url:"get_count.php",
success:function(response){
document.getElementById("count").innerHTML = "Comment added ("+response.responseText+")";
}
});
}
// ]]>
</script>
<?php $time = date("D, jS \of M Y");?>
</head>
<body>
<div class="container">
<form id="submit" method="post">
<p>
Name:<input id="name" value="">
<br>
Comment:<textarea cols="40" rows="3" id="comment"></textarea><br>
<input type="text" id="id" value="<?php echo $_GET['id']; ?>" size="2">
<input type="text" id="dateadded" value="<?php echo $time;?>" size="5">
<input name="submit" type="submit" class="button" value="Add Comment">
<input name="reset" type="reset" class="button" onclick="javascript:toggleLayer('commentForm');" value="Cancel">
</p>
</form>

<div class="success" style="display:none;" id="count">Comment added (comment count needs to update here...)</div>

</div>
<script type="text/javascript">
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var name = $('#name').attr('value');
var comment = $('#comment').attr('value');
var id = $('#id').attr('value');
var dateadded = $('#dateadded').attr('value');

$.ajax({
type: "POST",
url: "ajax.php",
data: "name="+ name + "&" + "comment=" + comment + "&" + "id=" + id + "&" + "dateadded=" + dateadded,
success: function(del){
$('form#submit').hide();
$('div.success').fadeIn();
updateCount();
}
});
return false;
});
});
</script>
</body>
</html>

student101
12-23-2008, 08:30 PM
I get Comment added (undefined)

This is based on ID so get_count.php should be get_count.php?id='$_GET[id]'

I really don't think it's possible to update the comment count after the insert.
I am open to suggestions, if jQuery can't do it what can?

Cheers

itsallkizza
12-23-2008, 09:10 PM
I really don't think it's possible to update the comment count after the insert- It definitely is



if jQuery can't do it what can?- jQuery can do it, did the code I gave you work when you added the ?id=id ? It's possible jQuery doesn't pass the response object into the success handler like I presumed. You'll have to look into their library descriptions to see how to retrieve the response.

student101
12-23-2008, 09:17 PM
When I add the ?id=id (used 1 and added a couple of 1's) it gave me undefined.
I know there is a method to do this without a page refresh.

It just needs requery the database or call the db value.

itsallkizza
12-23-2008, 11:19 PM
All you need is a function that sends an ajax request to a server-side intermediary which in turn requests the data from your database. The JS handler for your request will then update your html count.

It's as simple as that.

If you insist on using jQuery, I'm done helping you (already gave you a concept function for jQuery - you're undefined response could be for a number of reasons). If you want to build your own xmlhttprequest object and handlers, go for it and I can help you debug any problems you run into, it's really rather simple.

student101
12-24-2008, 06:39 AM
All new to jQuery, Ajax and JS, found a method to add a comment without a page refresh.
Yes it's jQuery, but aren't they all?

I don't insist on using anything, I am happy to go with what ever works.
You said that jQuery can do it.


I have a few ebooks;

Ajax: Creating Web Pages with Asynchronous JavaScript and XML

AJAX and PHP -

Building Responsive Web Applications

Ajax For Dummies 2006

Beginning JavaScript with DOM Scripting and Ajax: From Novice to Professional



It's up to me to read them and maybe they can give me insight to this basic yet complicated issue.

itsallkizza, I do appreciate your help, Thank you!

itsallkizza
12-24-2008, 07:48 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Example</title>
<style type="text/css">
</style>
<script type="text/javascript">
// <![CDATA[

function XML_HTTP_Util()
{
this.sendRequest = function(url,async,callback,callbackargs)
{
var req = this.createXMLHTTPObject();
if (!req) callback.call(this,false,callbackargs);
req.ref = this;
req.open("GET",url,async);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
req.onreadystatechange = function()
{
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304)
{
//alert("HTTP error " + req.status);
callback.call(this.ref,false,callbackargs);
}
else
{
callback.call(this.ref,req,callbackargs);
}
}
if (req.readyState == 4) return;
req.send(null);
}
this.createXMLHTTPObject = function()
{
var xmlhttp = false;
for (var i=0;i<this.XMLHttpFactories.length;i++)
{
try
{
xmlhttp = this.XMLHttpFactories[i]();
}
catch(e)
{
continue;
}
break;
}
return xmlhttp;
}
this.XMLHttpFactories = [
function() {return new XMLHttpRequest()},
function() {return new ActiveXObject("Msxml2.XMLHTTP")},
function() {return new ActiveXObject("Msxml3.XMLHTTP")},
function() {return new ActiveXObject("Microsoft.XMLHTTP")}
];
}

function updateCounter()
{
var my_xmlhttputil = new XML_HTTP_Util();
var handleCount = function(response)
{
document.getElementById("count").innerHTML = "Comment added ("+response.responseText+")";
}
my_xmlhttputil.sendRequest("get_count.php?id=23",true,handleCount);
}

// ]]>
</script>
</head>
<body>

<div id="count"></div>

</body>
</html>


Change the id=23 to whatever you want and make sure your get_count.php?id=# works on its own first, then try the ajax.

student101
12-24-2008, 07:54 AM
Thanks but nothing gets displayed, blank page.
What needs to call the get_count.php?

Have to add updateCount(); at the end after last "}" to display the data.
Only issue is that it's not dynamic. In the sense that the id is in the URL with GET[id]

itsallkizza
12-24-2008, 09:05 AM
Thanks but nothing gets displayed, blank page.- What's a blank page? get_count.php? I can't help you with that one because I don't have access to your database - so I'd have no idea what you're doing wrong.

If your comments id is inserted via PHP on load, then do so, I don't see the problem:

function updateCounter()
{
var my_xmlhttputil = new XML_HTTP_Util();
var handleCount = function(response)
{
document.getElementById("count").innerHTML = "Comment added ("+response.responseText+")";
}
my_xmlhttputil.sendRequest("get_count.php?id=<?php echo($_GET['id']) ?>",true,handleCount);
}

student101
12-24-2008, 09:27 AM
I didn't know that you could add the PHP values directly into the jscript like that, pretty cool.

It works once I add in the PHP
Only thing; In IE7 it shows once in FireFox it shows all the time after a page refresh/reload.
Any ideas there?
FIXED!!! Changed GET to POST
The code from the get_count.php is this;

<?php
$sql = "SELECT COUNT(*) AS count FROM comments WHERE id = '$_GET[id]'";
$result = mysql_query($sql);
if($result){
$row = mysql_fetch_row($result);
$count = $row[0];
echo $count;
} else{
echo "Err";
}
?>

This is so unbelievable :thumbsup: THANK YOU!!!
WOW how cool is this!

itsallkizza
12-24-2008, 03:43 PM
Glad I could help :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum