CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Ajax and Design (http://www.codingforums.com/forumdisplay.php?f=55)
-   -   How to update comment count? (http://www.codingforums.com/showthread.php?t=154739)

student101 12-22-2008 04:36 PM

How to update comment count?
 
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?

Edit: 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 08: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 02:56 PM

wait... what now?

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

student101 12-23-2008 04:39 PM

Quote:

Originally Posted by ohgod (Post 762641)
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.
Edit: Code added;

PHP Code:

<!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 04: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 04:45 PM

Just added it above.

Edit: PHP with MySQL
Here is ajax.php below;

PHP Code:

<?php
$con 
mysql_connect("localhost","user","pass");
if (!
$con) {
  die(
'Could not connect: ' mysql_error());
}
mysql_select_db("dbname"$con);
$commenthtmlspecialchars(trim($_POST['comment']));
$idhtmlspecialchars(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 Code:

<?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 06:14 PM

Quote:

Originally Posted by itsallkizza (Post 762694)
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 06: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:
Code:

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:
Code:

<!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 07:30 PM

I get Comment added (undefined)

Edit: 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 08:10 PM

Quote:

I really don't think it's possible to update the comment count after the insert
- It definitely is


Quote:

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 08: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 10: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 05: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 06:48 AM

Code:

<!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 06:54 AM

Thanks but nothing gets displayed, blank page.
What needs to call the get_count.php?
Edit:
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]


All times are GMT +1. The time now is 10:30 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.