Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts

    Question 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.
    Last edited by student101; 12-22-2008 at 05:52 PM.
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #2
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts
    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.
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #3
    Regular Coder ohgod's Avatar
    Join Date
    Jun 2008
    Location
    Ohio
    Posts
    579
    Thanks
    6
    Thanked 69 Times in 69 Posts
    wait... what now?

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

  • #4
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts

    Smile

    Quote Originally Posted by ohgod View Post
    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
    Last edited by student101; 12-23-2008 at 05:44 PM.
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #5
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    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).
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #6
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts
    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";
    }
    ?>
    Last edited by student101; 12-23-2008 at 06:00 PM.
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #7
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts

    Question

    Quote Originally Posted by itsallkizza View Post
    Ya, your code would be nice.
    In specific, the ajax request handler function and the div you want updated.
    Will that do?
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #8
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    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>
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #9
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts
    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
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #10
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    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.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #11
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts
    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.
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #12
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    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.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • #13
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts

    Thumbs up

    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!
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:

  • #14
    Senior Coder
    Join Date
    Oct 2008
    Location
    Long Beach
    Posts
    1,196
    Thanks
    36
    Thanked 164 Times in 164 Posts
    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.
    Feel free to e-mail me if I forget to respond ;)
    ohsosexybrit@gmail.com

  • Users who have thanked itsallkizza for this post:

    student101 (12-24-2008)

  • #15
    Regular Coder student101's Avatar
    Join Date
    Nov 2007
    Posts
    634
    Thanks
    80
    Thanked 15 Times in 15 Posts
    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]
    Last edited by student101; 12-24-2008 at 08:04 AM.
    Thanks for your support!
    Update MySQL with checkboxes | Tell A Friend | Delete MySQL with checkboxes

    Give thanks & resolve when done :thumbsup:


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •