I opened a question for a different issue that finally led to the one I now need help with. AJAX form Submit to post comments
I got a solution to the js errors I was getting but now the issue is something else.
I'm using a script I found here. Credits and Demo to original script
and it's meant to post comments without refreshing the page with a fadeIn effect. I modified it to fit my project and the issue I have now is that even tho' it is saving the data into the database, it's not loading the comments live. I have to manually refresh the page is I want to see the new content. Since it's not throwing any js errors in the developer console, I can't find what the issue is.
The Comments Section
<div class="comments">
<div class="top-title">
<h3>Messages</h3>
</div>
<ul class="level-1">
<div class="comment-block">
<?php while ($row = mysqli_fetch_array($res_post_select))
{
$PageID = $row['PageID'];
$Name = $row['Name'];
$Photo = $row['Photo'];
$PostDate = $row ['PostDate'];
$Comment = nl2br($row['Comment']);
?>
Posted on <?php echo DATE("F d, Y", strtotime($PostDate)) ?> at <?php echo DATE("g:i a", strtotime($PostDate)) ?>
<li>
<span class='comment'>
<span class='picture'>
<span><img src='users/images/<?php echo $Photo?>'></span>
</span>
<span class='content'><span class='mid-title'><b><?php echo $Name ?></b>, Said:</span><br><?php echo $Comment ?></span>
<span class='clear'></span>
</span>
</li>
<?php } ?>
The JS Credits
<script>
$(document).ready(function(){
var form = $('form');
var submit = $('#submit');
form.on('submit', function(e) {
//$('#submit').on('click', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'data/queries/comment-insert.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serialized data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Posting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see https://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Post Message').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
</script>
The comment-insert.php File
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
$ds = DIRECTORY_SEPARATOR;
$base_dir = realpath(dirname(__FILE__) . $ds . '..') . $ds;
include_once("{$base_dir}..{$ds}include{$ds}dbconfig.php");
include_once("{$base_dir}..{$ds}include{$ds}dbconnection.php");
$conn = dbconnect();
if(!empty($_POST['comment']))
{
$Name = mysqli_real_escape_string($conn, $_POST['Name']);
$PageID = mysqli_real_escape_string($conn, $_POST['PageID']);
$ID = mysqli_real_escape_string($conn, $_POST['ID']);
$Comment = mysqli_real_escape_string($conn, $_POST['comment']);
$sql = "INSERT INTO comments
(PageID, ID, Name, PostDate, Comment)
VALUES
('$PageID', '$ID', '$Name', now(), '$Comment')";
mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
}
?>
<!-- This is the mark up that should fadeIn after the data is inserted into the database.
You can refer to the demo found in the credited page -->
<li><span class='comment'>
<span class='picture'>
<span><img src='users/images/<?php echo $Photo ?>'></span>
</span>
<span class='content'><span class='title'><b><?php echo $Name ?></b>, Said:</span><br><?php echo $Comment ?></span>
<span class='clear'></span>
</span>
</li>
<?php
mysqli_close($conn);
endif
So, the ajax triggers the query found in comment-insert.php but it does not insert live and is not giving any js errors in the console. I have to manually refresh the page to view the comments which defeats the purpose of the live-comment idea.
I am actually making a guess here as to why it might not be working. It might be the order in which you are trying to do things. You are fading the HTML response before it is actually in the DOM. You need to have it in the DOM before you can actually fade it. So instead of doing
var item = $(data).hide().fadeIn(800); // fading while it is not in the DOM
$('.comment-block').append(item);
do
var item = $(data).hide();
$('.comment-block').append(item); // in the DOM
item.fadeIn(800);
Your PHP file does not seem to be sending (ECHOing) anything back to the javascript AJAX routine.
Try this. Change your comment-insert.php file like this:
<?php
$ds = DIRECTORY_SEPARATOR;
$base_dir = realpath(dirname(__FILE__) . $ds . '..') . $ds;
include_once("{$base_dir}..{$ds}include{$ds}dbconfig.php");
include_once("{$base_dir}..{$ds}include{$ds}dbconnection.php");
$conn = dbconnect();
if(!empty($_POST['comment']))
{
$Name = mysqli_real_escape_string($conn, $_POST['Name']);
$PageID = mysqli_real_escape_string($conn, $_POST['PageID']);
$ID = mysqli_real_escape_string($conn, $_POST['ID']);
$Comment = mysqli_real_escape_string($conn, $_POST['comment']);
$sql = "INSERT INTO comments
(PageID, ID, Name, PostDate, Comment)
VALUES
('$PageID', '$ID', '$Name', now(), '$Comment')";
mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
}
$Photo = 'your_image.jpg';
$out = "
<li><span class='comment'>
<span class='picture'>
<span><img src='users/images/" .$Photo. "'></span>
</span>
<span class='content'><span class='title'><b>" .$Name. "</b>, Said:</span><br>" .$Comment. "</span>
<span class='clear'></span>
</span>
</li>
";
echo $out;
?>
Note that the above code does not have a $Photo variable and will fail, so I provided one just so the code will not crash. Please fix as appropriate.
Using someone else's code is always challenging.
First, there is no need for a <form></form>
construct. Just use DIVs. That will remove the need to use e.preventDefault()
(which is only used to suppress the default <form>
behavior of navigating away from the current page).
Next, you only need to use .on()
if the element on which the user is clicking has been added into the DOM after it (the DOM) was originally rendered. The purpose of .on()
is to instruct the DOM to bind javascript code to an element that will appear later, but that is not yet in the DOM when the javascript code executes. In such a case, without .on()
, the user click would do nothing because the code could not bind to a button that did not yet exist.
Please review the simple AJAX examples in this post. Honestly, you can easily build this chat system yourself without using w3bee's code. However, after you built something that kinda works you might want to compare what you came up with to the w3bee code and see if they had any good ideas. But seriously, build it yourself. You will spend days troubleshooting w3bee's code (primarily because it remains a black box) but you can reproduce it yourself in mere hours.
Take the examples in the linked post, copy them to your server, and make them work. Especially this one. You will learn more in 20 minutes playing with these examples than you will in two days of tinkering with w3bee's code.
At the very least, making those examples work on your own system might help you realize what the problem is with the w3bee code you have now.
Having said the above, the problem with the current code is probably in the javascript AJAX success:
function. Try displaying what is received (from the PHP side) and see what you get:
$.ajax({
url: 'data/queries/comment-insert.php',
type: 'POST',
data: form.serialize(), //form serialized data
success: function(data){
alert(data);
}
});