Displaying existing content in editable textarea - javascript

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);
});

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"]?

Populating a HTML table using JQUERY, PHP and AJAX

I am trying to populate a HTML table using JQUERY, AJAX and PHP code. When I run my code, my table is displayed but it is filled with 'undefined'.
I have three pieces of code. Here is my HTML and jQuery:
var integer = $("#transfers_in").attr("name");
alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {
dataType: 'json',
myData: integer
}, // data to submit
success: function(response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var name = response[i].name;
var amount = response[i].amount;
var tr_str = "<tr>" +
"<td align='center'>" + (i + 1) + "</td>" +
"<td align='center'>" + name + "</td>" +
"<td align='center'>" + amount + "</td>" +
"</tr>";
$("#money_in").append(tr_str);
}
}
});
<table id="money_in">
<tr>
<th>Name</th>
<th>Amount(Million £)</th>
</tr>
</table>
and here is my PHP Code:
<?php
if (isset($_POST['myData'])) {
$integer = $_POST['myData'];
if ($integer === "1"){
include 'db_connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$return_arr = array();
$query = "SELECT * FROM `money_in_19_20`";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result)){
$name = $row['Name'];
$amount = $row['Amount'];
$return_arr[] = array("Name" => $name,
"Amount" => $Amount);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
}
The Json data is being received in the format of
{"Name":"Hazard","Amount":"103000000"}
You are returning object as Name,Amount and checking as name,amount
var name = response[i].name;
var amount = response[i].amount;
it should be
var name = response[i].Name;
var amount = response[i].Amount;

Posting data without refresh + calling another jquery function

My code, basically, on a click of a button, runs an ajax function in order to write stuff to my database.
What I want to do next is call another function which will fetch data from the database and print it.
Here is my code below, but the second function does not show that it works. I don't know where I went wrong.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function loaddata() {
$.ajax({
type: "POST",
url: "includes/fetchupdatedimages.php",
data: $("#editad_form").serialize(),
success: function (response) {
alert(response);
}
});
});
</script>
Second function:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$("#deleteimgs").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/deleteimages.php",
data: $("#editad_form").serialize()
});
$("input[type=checkbox]:checked").parent().remove();
loaddata();
});
});
</script>
fetchupdatedimages.php
<?php
include_once "functions.php";
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
error_reporting(E_ALL);
$id = $_POST["id"];
if ($stmt = $mysqli->prepare("SELECT images FROM db WHERE id = ? LIMIT 1")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($images);
$stmt->fetch();
}
echo "<p>" . $images . "</p>";
?>
It seems that loaddata() does not get called or it does not return any data to me back. Any help?
Have you tried sending the data from your PHP file using JSON over to your jQuery code instead?
For example:
PHP
<?php
header("Content-Type: application/json");
include 'connect.php';
$sql = "SELECT * FROM reviews, customers WHERE review_user = customer_id";
$datas = "";
$x = 0;
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$datas[$x] = array("fname" => $row["customer_name"], "lname" => $row["customer_surname"], "email" => $row["customer_email"], "gender" => $row["customer_gender"], "title" => $row["review_title"], "content" => $row["review_content"], "rating" => $row["review_rating"]);
$x++;
}
}
$con->close();
echo json_encode($datas);
?>
jQuery
$(document).ready(function() {
$.getJSON('controls/getReviews.php', function(jsondata) {
console.log("Returned data: " + jsondata);
if (jsondata !== "") {
for (var i = 0; i < jsondata.length; i++) {
var data = jsondata[i];
var fname = data["fname"];
var lname = data["lname"];
var email = data["email"];
var gender = data["gender"];
var title = data["title"];
var msg = data["content"];
var rating = data["rating"];
$('.reviews').append('<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">' + title + '</h3></div><div class="panel-body"><table class="table table-striped"><tr><td>Name:</td><td>' + fname + ' ' + lname + '</td></tr><tr><td>Gender:</td><td>' + gender + '</td></tr><tr><td>Rating:</td><td>' + rating + '/5</td></tr><tr><td>Message:</td><td>' + msg + '</td></tr></table></div></div>');
}
}
});
});

JavaScript/AJAX prints weirdly

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.

Drag and Drop using jQuery Save the new order

i'm using drag and drop to order a list with jquery ....
and i want to save the new order to Database by clicking a button for exemple
this is my methode to get list element
public function test() {
$choice = Database::getInstance()->query("SELECT * FROM choix WHERE condidat_concour_id = ".$this->data()->ID." ORDER BY ordre ASC");
foreach($choice->results() as $choi){
$cs_code = $choi->cs_code;
$cs = Database::getInstance()->query("SELECT code,designation,site
FROM cs
WHERE code = '{$cs_code}' ");
echo "<li id=".$choi->id.">";
echo "<span class='handle'><i class='fa fa-ellipsis-v'></i><i class='fa fa-ellipsis-v'></i></span>";
echo "<span class='text'>".$choi->cs_code."</span>";
echo "</li>";
}
}
I'm looking to use this Script to save order
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('id');
else
articleorder += "," + $(this).attr('id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('set_order.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
but i don't know what i should use in set_order.php ??
i'm trying with this code but i didn't get any result !!
$i = 1 ;
$orderlist = explode(',', $_POST['ordre']);
foreach ($orderlist as $k=>$order) {
$sql = 'UPDATE choix SET ordre = :ordre WHERE id = :id' ;
$query = $pdo->prepare($sql);
$query->bindParam(':ordre', $i, PDO::PARAM_INT);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$i++ ;
}
you can check my Database classe here

Categories