Jump to content

My first simple Ajax powered comment system - doesn't work :(


V

Recommended Posts

Today I have been learning about Ajax and I'm trying to use it in a simple functional comment system I set up. I have a post.php which displays a post and in that I include the comments.php which shows all the comments the belong to the post. The comments.php is this

 

<html>
<head>
<link href="stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","insert_comment.php",true);
xmlhttp.send();
}
</script>
</head>
<body>


<?php require_once("/js_scripts/js_comments.php"); ?>
<?php require_once("functions.php"); ?>

<?php

$connection = dbConnect();

//$post_id value comes from the POSTS table
$post_id = $_GET['post'];

// prepare the SQL query
$sql = "SELECT * FROM comments WHERE post_id=$post_id ORDER BY date desc";

$result = $connection->query($sql) or die(mysqli_error($connection));

while ($row = $result->fetch_assoc()) {	

//comment form vars
$com_name=$row['com_name'];
$com_email=$row['com_email'];
$com_dis=$row['com_dis'];

echo "<strong>$com_name</strong> <br />";
echo "$com_dis <br /><br />";
}

?>

<form action="#" method="post">
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>"/> 
<input type="text" name="com_name"/>Name<br />
<input type="text" name="com_email"/>Email<br />
<textarea name="com_dis" id="comment" style="height: 30px; display: inline;"></textarea>
<div id="button_block">
<input name="submit" onclick="loadXMLDoc()" type="submit" id="button" class="submit" value="Share "/>
<input type="submit" id="cancel" value="cancel" />
</div>
</form>

</body>
</html>

 

 

and insert_comments.php, the file that inserts the comments into the database contains,

 

$connection = @mysql_connect("localhost","user","pass") or die("Couldn't connect.");
$db = @mysql_select_db("gisttest", $connection) or die(mysql_error());

if ($_POST["submit"]) {  


$name = mysql_escape_string(strip_tags($_POST["com_name"]));
$email = mysql_escape_string(strip_tags($_POST["com_email"]));
        $comment = mysql_escape_string(strip_tags($_POST["com_dis"]));
        $comment = nl2br($comment);
$post_id = mysql_real_escape_string($_POST['post_id']);

	if (!$name || !$email || !$comment) {
	echo "Please go back and fill all fields.";
	exit;
	}

    $q = "INSERT INTO comments
                 (com_name, com_email, com_dis, post_id, date)
          VALUES ('$name', '$email', '$comment', '$post_id', NOW())";
		mysql_query($q, $connection) or die(mysql_error());


}

 

(I still need to modify the db connection into object oriented and use msql improved  :shy: ) Anyways, when I submit a new comment, something loads, I get no errors, but nothing is inserted into the database. I'm not sure where I'm doing something wrong..

 

 

Link to comment
Share on other sites

Thank you for pointing that out! I changed all the get to post and did some other modification and somehow I got form values in the address bar when submitting followed by some errors.. Making Ajax comments is maybe more complex than I anticipated. lol.. I'll do some more studying and give it another go tomorrow :)

Link to comment
Share on other sites

Post your updated code. It sounds like you switched the wrong part of the code to get.

 

Sure! This is the new comments.php. I just changed the form method to "get".

 

<html>
<head>
<link href="stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","insert_comment.php",true);
xmlhttp.send();
}
</script>
</head>
<body>


<?php require_once("/js_scripts/js_comments.php"); ?>
<?php require_once("functions.php"); ?>

<?php

$connection = dbConnect();

//$post_id value comes from the POSTS table
$post_id = $_GET['post'];

// prepare the SQL query
$sql = "SELECT * FROM comments WHERE post_id=$post_id ORDER BY date desc";

$result = $connection->query($sql) or die(mysqli_error($connection));

while ($row = $result->fetch_assoc()) {	

//comment form vars
$com_name=$row['com_name'];
$com_email=$row['com_email'];
$com_dis=$row['com_dis'];

echo "<strong>$com_name</strong> <br />";
echo "$com_dis <br /><br />";
}

?>

<form action="insert_comment.php" method="get">
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>"/> 
<input type="text" name="com_name"/>Name<br />
<input type="text" name="com_email"/>Email<br />
<textarea name="com_dis" id="comment" style="height: 30px; display: inline;"></textarea>
<div id="button_block">
<input name="submit" onclick="loadXMLDoc()" type="submit" id="button" class="submit" value="Share "/>
<input type="submit" id="cancel" value="cancel" />
</div>
</form>

</body>
</html>

 

and then the script that inserts the comment into the database. I changed all POST to GET.

 

 

 

require_once("functions.php");

$connection = dbConnect(); //DB connect function

if (isset($_GET["submit"])) {    

$name = $connection->real_escape_string(strip_tags($_GET["com_name"]));
$email = $connection->real_escape_string(strip_tags($_GET["com_email"]));
        $comment = $connection->real_escape_string(strip_tags($_GET["com_dis"]));
        $comment = nl2br($comment);
$post_id = $connection->real_escape_string($_GET['post_id']);

	if (!$name || !$email || !$comment) {
	echo "Please go back and submit a new post.";
	exit;
	}

    $sql = "INSERT INTO comments
                 (com_name, com_email, com_dis, post_id, date)
          VALUES ('$name', '$email', '$comment', '$post_id', NOW())";

   			$result = $connection->query($sql) or die(mysqli_error($connection));



}

else {
	echo "Access Denied";
}

 

 

So when I submit a comment the url goes to insert_comment.php and I get this

 

insert_comment.php?post_id=9&com_name=Jake&com_email=jake@someemail.com&com_dis=hellow world&submit=Share+
Link to comment
Share on other sites

It doesn't look like you're actually sending the GET variables. This line:

xmlhttp.open("GET","insert_comment.php",true);

indicates that you are NOT passing those get variables, because you are just sending to "insert_comment.php" when you should be sending to something like "insert_comment.php?someVariable=someValue".

Link to comment
Share on other sites

Hmmm I see. I changed that to

 

xmlhttp.open("GET","insert_comment.php?somevariable="+str,true);

 

but I'm not exactly sure what to do with the value. It's sending the comments to the DB but on submit it takes me to insert_comment.php

Link to comment
Share on other sites

Oh, no wonder. The problem is that you are posting to insert_comment.php like a traditional form (non-Ajax). Change your submit input types to button types. Also, "xmlhttp.open('GET','insert_comment.php?somevariable='+str,true);" will pass into the insert_comment.php file $_GET['somevariable'] witch will have whatever value your JS variable str happens to be.

Link to comment
Share on other sites

Oooh! Ok  I changed the form to this.

 

<form action="insert_comment.php" method="get">
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>"/> 
<input type="text" name="com_name"/>Name<br />
<input type="text" name="com_email"/>Email<br />
<textarea name="com_dis" id="comment" style="height: 30px; display: inline;"></textarea>
<div id="button_block">
<input type="button" name="submit" onclick="loadXMLDoc()" id="button" class="submit" value="Share "/>
<input type="submit" id="cancel" value="cancel" />
</div>
</form>

 

and wrapped the comments in myDiv which should display any new submitted comment

 

 

while ($row = $result->fetch_assoc()) {	

//comment form vars
$com_name=$row['com_name'];
$com_email=$row['com_email'];
$com_dis=$row['com_dis'];

?>

    <div id="myDiv">
<strong><?php echo $com_name?></strong><br />
<?php echo $com_dis?><br /><br />
    </div>

<?php } ?>

 

now however when I click the submit button nothing happens :-\ Shouldn't it process the insert_comment.php?

Link to comment
Share on other sites

Ok, thank you so much for helping out!

 

comments.php

 

<html>
<head>
<link href="stylesheets/style.css" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","insert_comment.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>


<?php require_once("/js_scripts/js_comments.php"); //just some jquery effects for the comment textarea, makes it slide on click and adds a default text ?>
<?php require_once("functions.php"); ?>

<?php

$connection = dbConnect();

//$post_id value comes from the POSTS table
$post_id = $_GET['post'];

// prepare the SQL query
$sql = "SELECT * FROM comments WHERE post_id=$post_id ORDER BY date desc";

$result = $connection->query($sql) or die(mysqli_error($connection));

while ($row = $result->fetch_assoc()) {	

//comment form vars
$com_name=$row['com_name'];
$com_email=$row['com_email'];
$com_dis=$row['com_dis'];

?>

    <div id="myDiv">
<strong><?php echo $com_name?></strong><br />
<?php echo $com_dis?><br /><br />
    </div>

<?php } ?>


<form action="insert_comment.php" method="post">
<input type="hidden" name="post_id" value="<?php echo $post_id; ?>"/> 
<input type="text" name="com_name"/>Name<br />
<input type="text" name="com_email"/>Email<br />
<textarea name="com_dis" id="comment" style="height: 30px; display: inline;"></textarea>
<div id="button_block">
<input type="button" name="submit" onclick="loadXMLDoc()" id="button" class="submit" value="Share "/>
<input type="submit" id="cancel" value="cancel" />
</div>
</form>

</body>
</html>

 

 

insert_comment.php

 

require_once("functions.php");

$connection = dbConnect(); //DB connect function

if (isset($_GET["submit"])) {    

$name = $connection->real_escape_string(strip_tags($_GET["com_name"]));
$email = $connection->real_escape_string(strip_tags($_GET["com_email"]));
    $comment = $connection->real_escape_string(strip_tags($_GET["com_dis"]));
    $comment = nl2br($comment);
$post_id = $connection->real_escape_string($_GET['post_id']);

	if (!$name || !$email || !$comment) {
	echo "Please go back and submit a new post.";
	exit;
	}

    $sql = "INSERT INTO comments
                 (com_name, com_email, com_dis, post_id, date)
          VALUES ('$name', '$email', '$comment', '$post_id', NOW())";

   			$result = $connection->query($sql) or die(mysqli_error($connection));



}

else {
	echo "Access Denied";
}

 

those are all the files I'm using for comments. Without ajax it works, no db errors.

Link to comment
Share on other sites

OK, I see two main problems. First, the "myDiv" div is being displayed within your while loop, rather than wrapping around it. If you viewed the HTML source of your page, you would see as many "myDiv" divs as you have rows. So, change those lines from this:

while ($row = $result->fetch_assoc()) {









//comment form vars



$com_name=$row['com_name'];



$com_email=$row['com_email'];



$com_dis=$row['com_dis'];






?>




    <div id="myDiv">



<strong><?php echo $com_name?></strong><br />



<?php echo $com_dis?><br /><br />
    </div>

<?php } ?>

to this:

<div id="myDiv">
<?php
while ($row = $result->fetch_assoc()) {

//comment form vars
$com_name=$row['com_name'];
$com_email=$row['com_email'];
$com_dis=$row['com_dis'];
?>

<strong><?php echo $com_name?></strong><br />
<?php echo $com_dis?><br /><br />

<?php } ?>
</div>

 

The second problem, which is the bigger one, is that your insert_comment.php file isn't printing out the newly inserted row(s). You are printing out the comments when the page initially loads, but then that information is static. Calling your Ajax stuff isn't going to re-populate that stuff unless you tell it to. This may need to be cleaned up, but try this for your insert_comment.php file:

require_once("functions.php");
$connection = dbConnect(); //DB connect function
if (isset($_GET["submit"])) {    
$name = $connection->real_escape_string(strip_tags($_GET["com_name"]));
$email = $connection->real_escape_string(strip_tags($_GET["com_email"]));
    $comment = $connection->real_escape_string(strip_tags($_GET["com_dis"]));
    $comment = nl2br($comment);
$post_id = $connection->real_escape_string($_GET['post_id']);
if (!$name || !$email || !$comment) {
echo "Please go back and submit a new post.";
exit;
}
    $sql = "INSERT INTO comments
                 (com_name, com_email, com_dis, post_id, date)
          VALUES ('$name', '$email', '$comment', '$post_id', NOW())";
$result = $connection->query($sql) or die(mysqli_error($connection));

$sql = "SELECT * FROM comments WHERE post_id=$post_id ORDER BY date desc";
$result = $connection->query($sql) or die(mysqli_error($connection));
while ($row = $result->fetch_assoc()) {
//comment form vars
$com_name=$row['com_name'];
$com_email=$row['com_email'];
$com_dis=$row['com_dis'];
?>
<strong><?php echo $com_name?></strong><br />
<?php echo $com_dis?><br /><br />
<?php }
} else {
echo "Access Denied";
}

Link to comment
Share on other sites

Thanks F1Fan! I applied your code and cleaned up the second but I think there's an issue with the submit button. Nothing happens when I press it.

 

It looks like this

 

<input type="button" name="submit" onClick="loadXMLDoc()" id="button" class="submit" value="Share "/>

 

I even tried removing the js that gives the textarea some jquery effect but still nothing happens. Maybe there's a glitch somewhere else in my site..

Link to comment
Share on other sites

Well, without any errors, it will be difficult to troubleshoot. Take a look at your JS error console (the Firebug add-on in Firefox is awesome) and post any errors that occur when you click the button.

 

If you look into the DB, is it inserting the data and just not displaying it, or is it not inserting either?

Link to comment
Share on other sites

Thank you for recommending the JS console! I didn't know Firebug can do that :) It seems to have 2 errors.

 

syntax error:

if (str=="") \n

 

and then when I click submit comment I get

 

loadXMLDoc() not defined

 

It's not inserting anything into the DB, it does however without the Ajax, using POST method and insert_comment.php as action. So right I just get that error when I click submit

Link to comment
Share on other sites

Let's start with the first error:

syntax error:

if (str=="") \n

I don't see that anywhere in your code. Post all the other JS you have (excluding any jQuery files). The error console and Firebug should both tell you what file and what line those errors are occurring on, so list that info, too.

Link to comment
Share on other sites

I'm sorry, I had used if(str=='') in a recent attempt but I changed back the script to how I posted it before. So now I get

 

syntax error

if (window.XMLHttpRequest)\n

 

in this section

 

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} 

 

and the same second error

 

loadXMLDoc is not defined
Link to comment
Share on other sites

update: I cleaned the script and I don't get the syntax error anymore. Now when I click submit I get

 

str is not defined

xmlhttp.open("GET","insert_comment.php?q="+str,true);

 

in

 

xmlhttp.open("GET","insert_comment.php?q="+str,true);

xmlhttp.send();

}

</script>

Link to comment
Share on other sites

update: Ok I think we're getting close :)

 

I removed the q=+str,true

 

and changed it to

 

xmlhttp.open("GET","insert_comment.php");

 

no errors, I think I kave to clean up some code in insert comment.php

Link to comment
Share on other sites

A few days ago a started enhancing my comment system with Ajax. Forum user F1Fan (whom I thank again for the relentless support!) helped me a lot and I was able to finally make it work.  ;D There are however just 2 minor issues (to my knowledge) that if fixed would make the script flawless (I think). Anyways here's the Ajax comment system. It's comprised of two files: comments.php which displays the comments of a certain post and insert_comment.php which inserts new comments into the DB.

 

comments.php

http://www.phpriot.com/2928

 

insert_comment.php

http://www.phpriot.com/2930

 

The issues are..

 

For some reason, when submitting the form you have to click the button 2 times. Lastly, after submitting the form it's still filled and you can click submit continuously and insert the same comment unlimited times. I'm not aware of any other issues. I'm hoping someone can help me finalize the form.  :)

 

 

Link to comment
Share on other sites

For the first one, maybe showing up some code on that would help us get to have a light pf what was going on.

 

For the second one, after sending, note that the page doesn't refresh so the previous information you sent won't be cleaned automatically. To do so, make a callback function instead and every after successful ajax, clean your form inputs.

 

My two cents.

 

bluejay,

Link to comment
Share on other sites

Just a thing I want to ask though. You were using jquery right (as you stated with the effect you were trying to achieve in some part)? How about you use the ajax method of jquery instead creating a new one?

 

Just a suggestion though so you won't have code duplication. ;)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.