Creating Ajax response and displaying it - php

If anyone could point me in the right direction with this code I would greatly appriciate it, tell me how to debugg or point me in the right direction.
When I click the save button, the database gets updated, what I want to do is to send the new data back to ajax and display it in the same columns as the inputs where.
Question: How do I return the data in a response from PHP to Ajax and update the columns with the new text?
I have implemented code from this thread into my project:
Allow editing of Text dynamic php table
This is my front end code:
<div class="planerarad momentrad" data-row="<?php echo $pmomentID; ?>" ondblclick="toggleaction<?php echo $pmomentID; ?>()">
<div data-column='name' class="ansvar <?php echo $rowp['status'];?>">
<?php echo $rowp['ansvarig'];?>
</div>
<div data-column='moment' class="moment <?php echo $rowp['status'];?>">
<?php echo $rowp['moment'];?>
</div>
<div data-column='deadline' class="deadline <?php echo $rowp['status'];?>">
<?php
echo $rowp['deadline'];?>
</div>
<div class="icon">
</div>
<div class="moment-meny">
<div class="m-current">
<?php if ($pstatus == 0) { ?>
<button type="button"><i class="far fa-question-circle"></i></button>
<?php
} elseif ($pstatus == 1) { ?>
<button><i class="fas fa-user-check"></i></button>
<?php
} elseif ($pstatus == 2) { ?>
<button><i class="fas fa-exclamation"></i></button>
<?php
} elseif ($pstatus == 3) { ?>
<button><i class="fas fa-check"></i></button>
<?php } ?>
</div>
<div class="ärendeadmin">
<div class="m-remove">
<form action="scripts/s_editPlan.php" method="post" id="deletePlan<?php echo $pmomentID; ?>">
<input type="hidden" name="momentid" value="<?php echo $pmomentID ;?>">
</form>
<button name="deleteMoment" type="submit" form="deletePlan<?php echo $pmomentID; ?>"><i class="fas fa-trash-alt"></i></button>
</div>
<div class="m-edit">
<button class="closeWindow btn-info"><i class='fas fa-edit'></i></button>
</div>
</div>
And here is the jquery to replace text with inputs and send to php file:
<script>
$( function(){
$(document).on("click", ".btn-info", function(){
var parent = $(this).closest(".momentrad");
var id = $(parent).attr("data-row");
var name = $(parent).children("[data-column='name']");
var moment = $(parent).children("[data-column='moment']");
var deadline = $(parent).children("[data-column='deadline']");
var nameTxt = $(name).html();
var momentTxt = $(moment).html();
var deadlineTxt = $(deadline).html();
$(name).html("<input class='input' list='users' name='name' data-dc='ansv' value='"+$.trim(nameTxt)+"'>");
$(moment).html("<input name='moment' data-dc='moment' value='"+$.trim(momentTxt)+"'>");
$(deadline).html("<input type='date' max='9999-12-31' data-dc='deadline' value='"+$.trim(deadlineTxt)+"' name='deadline'>");
$(this).replaceWith("<button class='btn-info-save'>Save</button>");
});
})
</script>
<script>
$(function(){
$(document).on("click", ".btn-info-save", function(){
var parent = $(this).closest(".momentrad");
var id = $(parent).attr("data-row");
var data = {id: id};
var name = $(parent).children("[data-column='name']");
var moment = $(parent).children("[data-column='moment']");
var deadline = $(parent).children("[data-column='deadline']");
$("[data-dc]").each( function(){
var col = $(this).attr("data-dc");
var val = $(this).val();
data[col] = val;
console.log(data);
});
$.ajax({
url: "scripts/s_editPlan.php", // Change this to your PHP update script!
type: 'POST',
dataType: 'json',
data: data,
success: function(ret){
$(name).html(data(ansv));
$(moment).html(data(moment));
$(deadline).html(data(deadline));
alert("Ändringen lyckades! '"+$.trim(deadlineTxt)+"' '"+$.trim(momentTxt)+"' '"+$.trim(nameTxt)+"' ");
console.log(ret.response);
},
error: function(ret){
console.log(ret.response);
alert("Ändringen lyckades inte, inget!");
}
});
});
})
</script>
This is the PHP file:
<?php
include "dbh-script.php";
header('Content-type: application/json');
if (isset($_POST['ansv'], $_POST['moment'], $_POST['deadline'], $_POST['id'])) {
$dataid = $_POST['id'];
$ansv = $_POST['ansv'];
$moment = $_POST['moment'];
$deadline = $_POST['deadline'];
$sql = "UPDATE todoaction SET ansvarig='$ansv', moment='$moment', deadline='$deadline' WHERE id='$dataid'";
if ($conn->query($sql) === TRUE) {
echo json_encode(print_r($_POST););
} else {
echo json_encode( ["response"=>"Någonting gick fel. Error: " . $sql . "<br>" . $conn->error] );
}
}
if (isset($_POST['momentid'])) {
$id = $_POST['momentid'];
}
if (isset($_POST['deleteMoment'])) {
$sql = "UPDATE todoaction SET status='4' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['acceptMoment'])) {
$sql = "UPDATE todoaction SET status='1' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['helpMoment'])) {
$sql = "UPDATE todoaction SET status='2' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['checkMoment'])) {
$sql = "UPDATE todoaction SET status='3' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {
header('Location: ../index.php?page=ärenden');
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
I'm aware that it might be alot of errors and strange coding since I'm trying to learn by doing.

Related

PHP SQL Change style of filtered data while still display all data

I hava a page with a list of data displayed from database table and a search bar.
When I filter the data by id, the searched data will be highlighted (background color change) but I need it to remain displaying the rest of data.
I managed to change the background color of searched data however if I search the data that is not in table, the Record not found not displayed.
<?php
$search_keyword = '';
if (isset($_POST['search'])) {
$search_keyword = $_POST['search'];
}
?>
<head></head>
<body>
<form name="searchForm" action="" method="POST">
<input type="text" id="search" name="search" placeholder="Enter Employee ID Search">
</form>
<?php
$sql_search = "";
if (!empty($search_keyword)) {
$sql_search = " WHERE id = '" . $search_keyword . "' ";
}
$sql1 = "SELECT id, name, address FROM employee";
$result = $conn->query($sql1);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
?>
<div class="row">
<div class="employee">
<?php
if ($row["id"] == $search_keyword) {
?>
<div class="red-bg">
<?php
} else {
?>
<div class="white-bg">
<?php
}
?>
<div class="col-md-2"><?php echo $row["id"] ?></div>
<div class="col-md-3"><?php echo $row["name"] ?></div>
<div class="col-md-5"><?php echo $row["address"] ?></div>
</div>
</div>
</div>
</div>
<?php
}
} else {
?>
<div class="row">
<div class="employee">
<div class="white-bg">
<?php echo "Record not found." ?>
</div>
</div>
</div>
<?php
}
?>
</body>
<script>
document.onkeydown = function(evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 13) {
//your function call here
document.searchForm.submit();
}
}
</script>
If I include the search keyword in query, I can display the Record not found when searching for data not in table however if I search data that is in table will only display and highlight 1 data.
$sql1 = "SELECT id, name, address FROM employee ". $sql_search ."";
So how do I display all data and highlight searched data that is in table and only display Record not found when search for data that is not in table?
I have managed to highlight/bold the search data while still display all the other data and will display a message Record not found if the data is not in table.
<?php
include("database.php");
$search_keyword = '';
if (isset($_POST['search'])) {
$search_keyword = $_POST['search'];
}
?>
<head>
</head>
<body>
<form name="searchForm" action="" method="POST">
<input type="text" id="search" name="search" placeholder="Enter Employee ID Search">
</form>
<?php
//query for searching
$sql_search_keyword = "";
if (!empty($search_keyword)) {
$sql_search_keyword = " WHERE id = '" . $search_keyword . "' ";
$sql_want_search = "SELECT id, name, address FROM employee" . $sql_search_keyword;
$result_want_search = $conn->query($sql_want_search);
if ($result_want_search->num_rows > 0) {
while ($row_want_search = $result_want_search->fetch_assoc()) {
$searched_data = $row_want_search["id"];
//query for displaying all data - if match with search will bold
$sql_display_searched = "SELECT id, name, address FROM employee";
$result_display_searched = $conn->query($sql_display_searched);
if ($result_display_searched->num_rows > 0) {
while ($row_display_searched = $result_display_searched->fetch_assoc()) {
if ($searched_data == $row_display_searched["id"]) {
//bold match
echo "<b>" . $row_display_searched["id"] . " " . $row_display_searched["name"] . " " . $row_display_searched["address"] . " </b><br>";
} else {
echo $row_display_searched["id"] . " " . $row_display_searched["name"] . " " . $row_display_searched["address"] . " <br>";
}
}
}
}
} else {
echo "Record not found.";
}
} else {
//Initial display all data before search
$sql_initial = "SELECT id, name, address FROM employee";
$result_initial = $conn->query($sql_initial);
if ($result_initial->num_rows > 0) {
while ($row_initial = $result_initial->fetch_assoc()) {
echo $row_initial["id"] . " " . $row_initial["name"] . " " . $row_initial["address"] . " <br>";
}
}
}
?>
</body>
<script>
document.onkeydown = function(evt) {
var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
if (keyCode == 13) {
//your function call here
document.searchForm.submit();
}
}
</script>

comments are not showing on godaddy

i am poorly trapped and also not getting any proper support from the Godaddy customer care. I have a comment section which is working perfectly on localhost and some other hosting but it is not working on Godaddy hosting. I don't understand, why this only occurs on godaddy.
Here is my html :
<div class="comment-form-container">
<form id="frm-comment">
<div class="input-row">
<input type="hidden" name="comment_id" id="commentId" placeholder="Name" /> <input class="input-field" type="text" name="name" id="name" placeholder="Name" />
</div>
<div class="input-row">
<textarea class="input-field" type="text" name="comment" id="comment" placeholder="Add a Comment"> </textarea>
</div>
<div>
<input type="button" class="btn-submit" id="submitButton" value="Publish" /><div id="comment-message">Comments Added Successfully!</div>
</div>
</form>
</div>
<div id="output"></div>
Here is my script :
function postReply(commentId) {
$('#commentId').val(commentId);
$("#name").focus();
}
$("#submitButton").click(function () {
$("#comment-message").css('display', 'none');
var str = $("#frm-comment").serialize();
$.ajax({
url: "comment-add.php",
data: str,
type: 'post',
success: function (response) {
//var result = eval('(' + response + ')');
//var result = eval('(' + JSON.stringify(response) + ')');
if (response) {
$("#comment-message").css('display', 'inline-block');
$("#name").val("");
$("#comment").val("");
$("#commentId").val("");
listComment();
} else {
alert("Failed to add comments !");
return false;
}
}
});
});
$(document).ready(function () {
listComment();
});
function listComment() {
$.post("comment-list.php",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{
comments = "<div class='comment-row'>"+
"<div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + commentId + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$("#output").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "<div class='comment-row'>"+
" <div class='comment-info'><span class='commet-row-label'>from</span> <span class='posted-by'>" + data[i]['comment_sender_name'] + " </span> <span class='commet-row-label'>at</span> <span class='posted-at'>" + data[i]['date'] + "</span></div>" +
"<div class='comment-text'>" + data[i]['comment'] + "</div>"+
"<div><a class='btn-reply' onClick='postReply(" + data[i]['comment_id'] + ")'>Reply</a></div>"+
"</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
And I am 100% sure that there is no connectivity problem with database. Please help me out.
here is comment-add.php
<?php
require_once ("db.php");
date_default_timezone_set('Asia/Kolkata');
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$commentSenderName = isset($_POST['name']) ? $_POST['name'] : "";
$date = date("Y-m-d H:i:s", time());
$sql = "INSERT INTO tbl_comment(parent_comment_id,comment,comment_sender_name,date) VALUES ('" . $commentId . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
?>
here is comment-list.php
<?php
require_once ("db.php");
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
?>
here is db.php
<?php
$conn = mysqli_connect("localhost","xxxxxxxxx","xxxxxxxx","xxxxxxxxxx");
?>

Select results from live search ajax

I am new to this so an early sorry if my question useless... :) I want to be able to click on a result of a search output (the same as a dropdown menu except it's with a search bar) I have looked on internet but nothing could interest me. Thank you. PS: the connection of my database is in an other code but that shouldn't be useful.
Here is my code so far :
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche" class="search" onkeypress="showdiv()">
</div>
<div class="resultat" id="resultat" id="resultat" style="display: none;">
<a>Please continue typing...</a>
<br>
<br>
<br>
<br>
</div>
<script type="text/javascript">
function showdiv() {
document.getElementById("resultat").style.display = "block";
}
</script>
PHP:
<?php
include 'connect.php';
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$sql = "SELECT name FROM smartphone WHERE name LIKE '%" . $motclef . "%' LIMIT 5";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
} else {
echo "Aucun resultat trouvé pour: " . $motclef;
}
}
?>
jQuery:
$(document).ready(function(){
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#recherche').keyup(function() {
delay(function(){
var recherche = $('#recherche').val();
if (recherche.length > 1) {
$("#resultat").html("");
$.get( "fetch.php", { motclef: recherche} )
.done(function( data ) {
$("#resultat").html(data);
});
}
}, 1000 );
});
});
First-page.php
<?php
global $wpdb;
$supplier_prod_table=$wpdb->prefix.'supplier_product_post';
$sup_query=$wpdb->get_results("SELECT * FROM $supplier_prod_table");
$supp_name_chek=$user_info->user_login;
?>
<div class="form-group">
<input name="keysearch" value="<?php if($supp_name_chek!='') { echo $supp_name_chek; }?>" placeholder="name" id="keysearch" type="text" class="form-control">
<input type="hidden" value="" id="supplier_id">
<span id="loading">Loading...</span> </div>
db page
if(isset($_POST['keysearch']))
{
include('../../../../wp-load.php');
global $wpdb;
$search = $_POST['search'];
$table_name= $wpdb->prefix.'users';
$data = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `user_nicename` like '%$search%' OR `display_name` like '%$search%'");
foreach($data as $key)
{
$user_id=$key->ID;
$user = new WP_User( $user_id );
$role=$user->roles[0];
if($role=='supplier'){
$username = $key->user_login;
?>
<div class="search_show" align="left" id="<?php echo $user_id ?>"><?php echo $username; ?></div>
<?php
// echo "<div class='show' onclick='select_supp()'>".$username."</div>";
}
}
}
JS Code
jQuery(document).ready(function(){
jQuery('#keysearch').on('keyup', function(){
var ajax_search_url=search_url;
var key = jQuery('#keysearch').val();
if (key && key.length > 2)
{
jQuery('#loading').css('display', 'block');
jQuery.ajax({
url : ajax_search_url,
type : 'POST',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
jQuery('#loading').css('display', 'none');
jQuery("#search_result").html(data).show();
}
jQuery('#search_result .search_show').click(function() {
var text = jQuery(this).text();
var sid = jQuery(this).attr('id');
jQuery('#keysearch').val(text)
jQuery('#supplier_id').val(sid);
jQuery('#search_result').fadeOut(1000);
});
}
});
}
else
{
jQuery('#loading').css('display', 'none');
jQuery('#search_result').css('display', 'none');
}
});
});

unexpected end of input php jQuery

I have written same code at one machine and it is working fine but on other machine same code is giving error unexpected end of input. This is driving me crazy as why it is happening. Anybody who can help, please. These are my files with which I am working.
edit: I am making a small online test application for learning purpose. As the test start, the first question appears, on clicking next button the url changes to what it should be but next question does not appear and the error in the console says unexpected end of input. Since all my brackets are ok, I am not able to find error. Please help!!
TestStart.php
<?php
session_start();
if(isset($_SESSION['TestId']))
{
$TestId = $_SESSION['TestId'];
}
include('Config.php');
include('Reference.php');
$query = "select * from testquestions where testid='".$TestId."'";
$res = mysql_query($query);
if(mysql_num_rows($res) > 0)
{
$z = array();
while($fetch = mysql_fetch_array($res))
{
$z[]=$fetch['QId'];
}
$y = implode(",", $z);
$_SESSION['QIds']=$z;
}
else{
echo mysql_error();
}
?>
<body>
<div class="container">
<div class="row">
<div class="col-md-12" id="resultDiv">
<div class="col-md-12" id="qtext"></div>
<div class="col-md-12">
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionA"name="options" value="A"><span id="optA"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionB" name="options" Value="B"><span id="optB"></span>
</div>
</div>
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionC" name="options" value="C"><span id="optC"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionD" name="options" value="D"><span id="optD"></span>
</div>
</div>
</div>
<div id="nextbuttondiv"></div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
<?php
if(isset($_GET['qno'])&&isset($_GET['qindex']))
{
$qno = $_GET['qno'];
$qindex = $_GET['qindex'];
}
else{
$qno = '1';
$qindex = '0';
}
?>
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
var qidsarrCm = '<?php echo $y;?>';
var arrQid = qidsarrCm.split(",");
var totalQuestions = arrQid.length;
$.ajax({
type : "post",
url : "GetQuestionForTest.php",
data : {
"quId" : arrQid[qindex]
},
dataType : "json",
success : function(data){
alert('xy');
console.log(data);
$.each(data, function(){
var qText = this.questiontext;
var optionA = this.OptionA;
var optionB = this.OptionB;
var optionC = this.OptionC;
var optionD = this.OptionD;
var nxtBtn = this.NextButton;
$('#qtext').text(qText);
$('#optA').text(optionA);
$('#optB').text(optionB);
$('#optC').text(optionC);
$('#optD').text(optionD);
$('#nextbuttondiv').html(nxtBtn);
});
},
error: function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
$('input[type=radio]').on('click',function(){
$('.nxtbtn').removeAttr('disabled');
});
$('body').on('click','.nxtbtn', function(){
$.ajax({
type : "post",
url : "SaveTestAnswers.php",
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : <?php echo $_SESSION['CurrentUser'];?>,
"testId" : <?php echo $TestId;?>
},
dataType : "json",
success : function(data){
if(data.toString() == "true"){
qindex = qindex + 1;
qno = qno + 1;
if(qno > totalQuestions){
window.location.href="TestFinish.php";
}
else{
window.location.href="TestStart.php?qno="+qno+"&qindex="+qindex;
}
}
else{
alert(data + "Please resubmit the answer");
}
},
error : function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
});
});
</script>
</body>
GetQuestionForTest.php
<?php
$questionid = $_POST['quId'];
include('Config.php');
$query = "select * from questionstable where questionid = '".$questionid."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
$someArray = [];
while($fetch = mysql_fetch_array($result))
{
array_push($someArray,[
'questiontext' => $fetch['questiontext'],
'OptionA' => $fetch['optionA'],
'OptionB' => $fetch['optionB'],
'OptionC' => $fetch['optionC'],
'OptionD' => $fetch['optionD'],
'NextButton' => '<button class="btn btn-success nxtbtn" disabled >Next</button>'
]);
}
$someJSON = json_encode($someArray);
echo $someJSON;
}
else{
echo mysql_error();
}
?>
SaveTestAnswers.php
<?php
$qid = $_POST['qid'];
$ansId = $_POST['ansId'];
$stuId = $_POST['stuId'];
$testId = $_POST['testId'];
include('Config.php');
$query = "insert into testattemptedanswers(StudentId,TestId,QuestionId,AnswerGiven) values('".$stuId."','".$testId."','".$qid."','".$ansId."')";
$res = mysql_query($query);
if($res){
echo 'true';
}
else{
echo 'false'.mysql_error();
}
?>
Missing quotes -
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
Change them to -
var qno = '<?php echo $qno;?>';
var qindex = '<?php echo $qindex;?>';
And here also -
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : '<?php echo $_SESSION['CurrentUser'];?>',
"testId" : '<?php echo $TestId;?>'
},

Index page comments not inserting into database using AJAX

I'm trying to insert a comment into a database but I keep getting an Object object alert whenever trying to submit it and it never makes it to the database. The files are all in the same folder.
Any help is appreciated, thanks in advance.
index.php
<?php require_once('include/header.php'); require_once('include/browser.php'); ?>
<div class="content">
<section>
<div class="article">
<?php
$userNameQuery = "SELECT * FROM (SELECT * FROM `tbl_posts` ORDER BY 'post_id' DESC)
t ORDER BY `post_id` DESC
LIMIT 3";
$result = mysqli_query($connection, $userNameQuery)
or die("Error in query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result)){
$post_id = $row ['post_id'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['post_title']; ?></h1>
</div>
<div class="textcontainer">
<?php echo $row['post_content']?>
</div>
<?php
if (!empty($row['imagePath'])) //This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="<?php echo $row['imagePath']; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['post_timestamp']; ?>
<b>Author :</b> Admin
</div>
<?php
//Selecting comments which correspond to the post
$selectCommentQuery = "SELECT * FROM `tbl_comments`
LEFT JOIN `tbl_users`
ON tbl_comments.tbl_comments_users_id = tbl_users.id
WHERE tbl_comments.tbl_comments_post_id ='$post_id'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
//showing the comments
echo '<div class="comment-block_' . $post_id .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Comment by: <?php echo $commentRow['username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['comment_content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['comment_timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['cleanUsername']) )
{
?>
<form method="POST" class="post-form" action="index.php" >
<label>New Comment</label>
<textarea name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $post_id ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once('include/footer.php'); ?>
comments.js
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('.comment',form);
if (comment.val().length > 1)
{
$.ajax({
url: 'postComments.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data so we can enter into database
beforeSend: function(){
//Changing submit button value text and disabling it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Please fill the field!");
}
});
});
postComments.php
<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
session_start();
require_once('ajaxconnection.php');
$connection2 = connectToMySQL();
$userId = $_SESSION['userID'];
$username = $_SESSION['cleanUsername'];
$comment = $_POST['comment'];
$postId = $_POST['post_id'];
$date_format = " Y-m-d g : i : s";
$time = date ($date_format);
$insertCommentQuery = "INSERT INTO `tbl_comments`
(`comment_content`,`tbl_comments_users_id`,`tbl_comments_post_id`)
VALUES ('$comment', $userId, $postId)";
$result = mysqli_query($connection,$insertCommentQuery);
$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
<div class="commentusername"><h1> Username :'.$username.'</h1></div>
<div class="commentcontent">'.$comment.'</div>
<div class="commenttimestamp">'.$time.'</div>
</div>';
echo json_encode($obj);
connectToMySQL(0);
endif?>
ajaxconnection.php
<?php
function connectToMySQL()
{
$connection2 = mysqli_connect("localhost","root","","ascaniobajada2ed8s")
or die('Error connecting to the database');
return $connection2;
}
?>
JQuery .Ajax returns error like this (jqXHR, textStatus, errorThrown). So use it like this to see the real error and not just object object
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}

Categories