JavaScript/AJAX prints weirdly - javascript

My JavaScript/AJAX prints comments. It's all good, until I want to insert/get more than one comment. It duplicates itself. This feels like a nesting/missed parenthesis problem in my code, but I can't be able to find it...
My JS code:
$(document).ready(function(){
var url = 'comment-get.inc.php';
$.getJSON(url, function(data) {
$.each(data, function(index, item) {
var t = '';
t += '<div class="comment_holder" id="_'+item.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+item.username+'<br>';
t += ''+item.date+'<br>';
t += '<button class="button2" type="button" id="'+item.id+'">Delete</button>';
t += '</div></div>';
t += ''+item.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
});
});
add_delete_handlers();
$('#postButton').click(function(){
comment_post_btn_click();
});
function comment_post_btn_click()
{
//text in textarea with username, page and date
var _username = $('#postUsername').val();
var _page = $('#postPage').val();
var _date = $('#postDate').val();
var _message = $('#postMessage').val();
if(_message.length > 0)
{
//proceed with ajax callback
$('#postMessage').css('border', '1px solid #ABABAB');
$.post("comment-set.inc.php",
{
task : "comment-set",
username : _username,
page : _page,
date : _date,
message : _message
}
).success(
function(data)
{
//Task: Insert html into the div
comment_set(jQuery.parseJSON(data));
console.log("ResponseText: " + data);
});
}
else
{
//text in area is empty
$('#postMessage').css('border', '1px solid #FF0000');
console.log("Comment is empty");
}
//remove text after posting
$('#postMessage').val("");
}
function add_delete_handlers()
{
$('.button2').each(function()
{
var btn = this;
$(btn).click(function()
{
comment_delete(btn.id);
});
});
}
function comment_delete(_id)
{
$.post("comment-del.inc.php",
{
task : "comment-del",
id : _id
}
).success(
function(data)
{
$('#_' + _id).detach();
});
}
function comment_set(data)
{
var t = '';
t += '<div class="comment_holder" id="_'+data.comment.id+'">';
t += '<div class="user"> <img src="src/img/page3_img7.jpg" alt="" class="img_inner fleft">';
t += '<div class="extra_wrapper">';
t += ''+data.comment.username+'<br>';
t += ''+data.comment.date+'<br>';
t += '<button class="button2" type="button" id="'+data.comment.id+'">Delete</button>';
t += '</div></div>';
t += ''+data.comment.message+'<br><br>';
t += '</div>';
$('.comment_holder').prepend(t);
add_delete_handlers();
}
});
Comments.php:
<?php
class Comments {
public function set($message, $username, $date, $page) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "INSERT INTO comments VALUES ('', '$username', '$page', '$date', '$message')";
$query = mysqli_query($connect, $sql);
if($query){
$std = new stdClass();
$std->id = mysqli_insert_id($connect);
$std->message = $message;
$std->username = $username;
$std->date = $date;
$std->page = $page;
return $std;
}
return null;
}
public function del($id) {
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "DELETE FROM comments WHERE id = $id";
$query = mysqli_query($connect, $sql);
if($query)
{
return true;
}
}
}
?>
Comment-get.inc.php:
<?php
$page = htmlentities("/index.php?page=maplepancakes", ENT_QUOTES);
$connect = mysqli_connect('localhost', 'root', '', 'trdb');
$sql = "SELECT * FROM comments WHERE page='$page' ORDER BY id DESC";
$result = $connect->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$row_data = array(
'id' => $row['id'],
'username' => $row['username'],
'date' => $row['date'],
'message' => $row['message']
);
array_push($data, $row_data);
}
?>
<?php
echo json_encode($data);
?>
Comment-set.inc.php:
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-set'){
$username = $_POST['username'];
$date = $_POST['date'];
$page = $_POST['page'];
$message = $_POST['message'];
require_once 'comments.php';
if(class_exists('Comments')){
$userInfo = $username;
$commentInfo = Comments::set($message, $username, $date, $page);
$std = new stdClass();
$std->user = $userInfo;
$std->comment = $commentInfo;
echo json_encode($std);
}
}
?>
Picture of the problem (json_encode in the bottom of the picture containing 3 comments):

your comments div container has class .comment_holder so each time with new comment you prepend to all class's so create comment container with unique id an prepend to this. like this $('#comment_container').prepend(t); this with work.

Related

Adding DropDown list in jQuery DataTable

I want to display table's data with jQuery DataTable and sometimes apply an extra data filtering, using the output of a dropdown select input.
The main code for fetching data (fetch.php) is:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["part_manufacturer"];
$sub_array[] = $row["part_id"];
$sub_array[] = $row["part_category"];
$sub_array[] = $row["part_stock"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
while the DataTable is defined in index.php as follows:
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"actions/fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 1],
"orderable":false,
},
],
});
In index.php, i've created 3 dependent dropdown lists, which load data from other tables. Now, i want to take the id of 3rd dropdown list and update the data of Part_tb in fetch.php accordingly. Below, you can see that when 3rd dropdown change, i call a function load_parts():
$(document).on('change', '#sub3_category_item', function(){
load_parts();
});
function load_parts()
{
var action = 'fetch_data';
var filter_part_id = $('#sub2_category_item').val();
$.ajax({
url:"actions/fetch.php",
method:"post",
data:{action:action, filter_part_id:filter_part_id},
success:function(data)
{
$('#user_data').DataTable().ajax.reload();
}
});
}
The problem is that i can't filter the data of fetch.php according to the selected id of #sub2_category_item. Could you help me on that?
I've modified the index.php as follows:
$(document).on('change', '#sub3_category_item', function(){
var filter_part_id = $('#sub3_category_item').val();
$('#user_data').DataTable().destroy();
fill_datatable(filter_part_id);
});
fill_datatable();
function fill_datatable(filter_part_id = '')
{
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"searching" : false,
"ajax":{
url:"actions/fetch.php",
type:"POST",
data:{filter_part_id:filter_part_id}
}
});
and fetch.php:
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST['filter_part_id']) && $_POST['filter_part_id'] != '')
{
$query .= "SELECT * FROM Part_tb WHERE part_id IN (SELECT pcfit_name from Part_car_fit_tb WHERE pcfit_id ='".$_POST["filter_part_id"]."') ";
}
but dataTable crashes, when #sub3_category_item is selected. Any idea, how to filter datatable with the value $_POST["filter_part_id"]?

Scrollbar won't go down when chat window is created

I'm currently working on a chat application which will support up to four windows simultaneously.
When I open a new chat-window, the scrollbar won't go down even though the function is called. Whenever I send a message it works fine.
function createChat(caller_id) {
$.ajax({
type: 'POST',
url: 'create_chat_interface.php',
data: {
caller_id: caller_id,
},
success: function(data) {
if (!$('#chat-history-' + caller_id).length) {
if ($.trim($("#chat1").html()) == '') {
$('#chat1').html(data);
document.getElementById("chat-close").id = 'chat-close1';
} else if ($.trim($("#chat2").html()) == '') {
$('#chat2').html(data);
document.getElementById("chat-close").id = 'chat-close2';
} else if ($.trim($("#chat3").html()) == '') {
$('#chat3').html(data);
document.getElementById("chat-close").id = 'chat-close3';
} else if ($.trim($("#chat4").html()) == '') {
$('#chat4').html(data);
document.getElementById("chat-close").id = 'chat-close4';
}
$('#chat-input-' + caller_id).focus();
scrollDown(caller_id);
}
}
})
}
function fetch_chat_history($caller_id, $db)
{
$query = "SELECT * FROM messages WHERE from_id = '$caller_id'
OR to_id = '$caller_id' ORDER BY timestamp ASC";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);
$output = '<ul>';
foreach ($result as $row) {
if ($row['from_id'] == $caller_id) {
$output .= '
<li class="received"><p>' . $row['message'] . '</p></li>';
} else {
$output .= '
<li class="sent"><p>' . $row['message'] . '</p></li>';
}
}
$output .= '</ul>';
return $output;
}

Is there any way to working with only one array with jQuery.each()?

I have a project where I filter the elements by clicking on the checkbox. I think biggest problem is with jQuery.each() function. You can see code below what it does. I need to create only one array and filter values only in this array, because now, i am getting duplicates. Is there any way how to fix this with jQuery.each() or i need to use another function? I know how this problem arises, but I didn't find a solution.
Of course, data for every checkbox are mixed. For example, some data fall under all checkboxes, another data only to one checkbox etc. You can see get_filter function.
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var brand = get_filter('brand');
var jackpot = get_filter('jackpot');
var volatility = get_filter('volatility');
var special_features = get_filter('special_features');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, brand:brand, jackpot:jackpot, volatility:volatility, special_features:special_features},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
console.log(filter);
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
fetch_data.php
<?php
//fetch_data.php
include 'template.php';
$pdo = pdo_connect_mysql();
if(isset($_POST["action"]))
{
$query = ('SELECT * FROM slotselect.slot WHERE 1');
$query2 = ('SELECT * FROM slotselect.slot, slotselect.slot_features, slotselect.special_features WHERE slot_features.id_slot = slot.id_slot AND slot_features.id_sf = special_features.id_sf');
if(isset($_POST["special_features"]))
{
$sf_filter = implode("','", $_POST["special_features"]);
$query .= " AND special_features.id_sf IN('".$sf_filter."') ";
$query2 .= " AND special_features.id_sf IN('".$sf_filter."') ";
}
if(isset($_POST["brand"]))
{
$brand_filter = implode("','", $_POST["brand"]);
$query .= " AND id_provider IN('".$brand_filter."') ";
$query2 .= " AND id_provider IN('".$brand_filter."') ";
}
if(isset($_POST["jackpot"]))
{
$jackpot_filter = implode("','", $_POST["jackpot"]);
$query .= " AND id_jackpot IN('".$jackpot_filter."') ";
$query2 .= " AND id_jackpot IN('".$jackpot_filter."') ";
}
if(isset($_POST["volatility"]))
{
$volatility_filter = implode("','", $_POST["volatility"]);
$query .= " AND id_vol IN('".$volatility_filter."') ";
$query2 .= " AND id_vol IN('".$volatility_filter."') ";
}
$statement = $pdo->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if(isset($_POST["special_features"]))
{
$statement = $pdo->prepare($query2);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$pom= $row['id_provider'];
$pom2= $row['id_slot'];
$provi = $pdo->prepare('SELECT logo FROM slotselect.provider WHERE id_provider = ?');
$provi->execute([$pom]);
$provik = $provi->fetch(PDO::FETCH_ASSOC);
$name = $pdo->prepare('SELECT name FROM slotselect.slot WHERE id_slot = ?');
$name->execute([$pom2]);
$namee = $name->fetch(PDO::FETCH_ASSOC);
$output .= '
<div class="col-sm-6 col-lg-4 col-xl-3 wow bounceInUp" data-wow-duration="1.4s" id="services">
<div class="box">
<div class="logo pasik">
<img src="admin/uploads/'. $provik['logo']. '" width="80" height="60">
</div>
<img src="admin/uploads/'. $row['image'] . '" width="100%" height="150">
<p></p>
<h4 class="title">'.$namee['name'].'</h4>
<p></p>
View
<p></p>
</div>
</div>';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
if($total_row > 0)
{
foreach($result as $row)
{
$pom= $row['id_provider'];
$pom2= $row['id_slot'];
$provi = $pdo->prepare('SELECT logo FROM slotselect.provider WHERE id_provider = ?');
$provi->execute([$pom]);
$provik = $provi->fetch(PDO::FETCH_ASSOC);
$name = $pdo->prepare('SELECT name FROM slotselect.slot WHERE id_slot = ?');
$name->execute([$pom2]);
$namee = $name->fetch(PDO::FETCH_ASSOC);
$output .= '
<div class="col-sm-6 col-lg-4 col-xl-3 wow bounceInUp" data-wow-duration="1.4s" id="services">
<div class="box">
<div class="logo pasik">
<img src="admin/uploads/'. $provik['logo']. '" width="80" height="60">
</div>
<img src="admin/uploads/'. $row['image'] . '" width="100%" height="150">
<p></p>
<h4 class="title">'. $namee['name']. '</h4>
<p></p>
View
<p></p>
</div>
</div>
';
}
}
else
{
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
?>
Some examples:
https://imgur.com/UbeZv72
https://imgur.com/DzMvIMe
https://imgur.com/NTIMbtg
If you just want to transmit one Array with all the ID's to your fetch_data.php you coud rewrite your js-code like this:
var filter_array = [
'brand',
'jackpot',
'volatility',
'special_features'
];
filter_data(filter_array);
function filter_data(filter_array)
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var selected_filters = get_filter(filter_array);
console.log(selected_filters);
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, filters:selected_filters}, //selected_filters Structure = [brand:'brand_value',jackpot:'jackpot_value', ... ]
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(filter_array, filter = []){
if (filter_array === undefined || filter_array.length == 0) { //check if array exists or if there are filters left to add
var class_name = filter_array.shift(); //Removes and returns first element of filter_array
$('.'+class_name+':checked').each(function(){
filter[class_name] = $(this).val();
get_filter(filter_array,filter); //called recursivly as long as there are filters to add
});
}
else{
return filter;
}
}
$('.common_selector').click(function(){
filter_data();
});
This might not use jquery.each() but it will produce an array with all the checked boxes names and values which you can iterate in you php by using foreach like this:
foreach($_POST['filters'] as $key => $value){
//$key = the name of the checkbox selector | $value = the value of the associated checkbox
}
This code is NOT TESTET, but i still hope it helps.

Display a php cookie in html

I have set a cookie using php.
Here's my code:
<?php
include_once 'php/config.php';
session_start(); //starting the session for user profile page
if(!empty($_POST['username'])) //checking the 'user' name which is from Sign-In.html, is it empty or have some text
{
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$query = mysql_query("SELECT * FROM users where username = '$username' AND password = '$password'") or die(mysql_error());
$row = mysql_num_rows($query) or die(mysql_error());
if($row==1)
{
$_SESSION['username'] = $username;
setcookie('username', $username, time() + (86400 * 30), "/"); // 86400 = 1 day
echo $_SESSION['username'];
echo "SUCCESSFULLY LOGGEDIN...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
echo "<script>setTimeout(function(){window.location.href='index.html'},2000);</script>";
}
}
?>
I want display the 'username' cookie in html like Hi ""
.
Please Help.
Tried this javascript:
<script type="text/javascript">
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
</script>
Use echo $_COOKIE['username']; instead of echo $_SESSION['username'];. It will echo out of the second reload of the page. (Why?)
<span id="myId"><span>
<script>
document.getElementById('myId').innerHTML=listCookies()
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}
</script>

Displaying existing content in editable textarea

Hi I am trying to make editable page with javascript and php and I want to display whats already stored in the area however it does not work. Its meant to be a blog page meaning that there are multiple posts. And I am unsure whether the problem is within the js or php.
This is the javascript I am using. The console.log() writes that post_id is unassigned.
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = '<textarea class="editPostBody">' + data.body + '</textarea>';
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});
});
var formatPost = function(d) {
var s = '';
s = '<div class="post" data-id="' + d.post_id + '"><h2 class="postHeading">' + d.title +'</h2>';
s += d.body;
s += '<p> Posted on: ' + d.date + '</p>';
s += '<div class="btn editButton">Edit Post</div>'
s += '</div>'
return s;
};
And this is the PHP file
connection to db established prior
if(count($_GET)) {
if(isset($_GET['post_id'])){
get_post_id( $_GET['post_id']);
}
}
else{
get_posts();
}
function get_posts() {
global $link;
// $sql = "SELECT COUNT(1) FROM posts";
// $result = mysqli_query($link, $sql);
// $total = mysqli_fetch_array($result);
$sql = "SELECT * FROM post ORDER BY date DESC LIMIT 0, 5";
$result = mysqli_query($link, $sql);
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
// $json = '{"total":"' . $total[0] . '","posts":';
$json = json_encode($rows);
// $json .= "}";
print($json);
}
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
Thank you
I modified the code like this
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE post_id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
and JS
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
// console.log(post_id);
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = $('<textarea class="editPostBody">' + data.body + '</textarea>');
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});

Categories