Count like and unlike php - javascript

I written a simple script where users can post without sign up or log in, something like conffesion website, people can post and get like and unlike on their posts. I want to count like then sort by most popular and most newest and show it on a main page, and I tried literally everything but nothing seems to work, heres my code:
comment-like-unlike.php
?php
require_once ("db.php");
$memberId = 1;
$commentId = $_POST['comment_id'];
$likeOrUnlike = 0;
if($_POST['like_unlike'] == 1)
{
$likeOrUnlike = $_POST['like_unlike'];
}
$sql = "SELECT * FROM tbl_like_unlike WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (! empty($row))
{
$query = "UPDATE tbl_like_unlike SET like_unlike = " . $likeOrUnlike . " WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
} else
{
$query = "INSERT INTO tbl_like_unlike(member_id,comment_id,like_unlike) VALUES ('" . $memberId . "','" . $commentId . "','" . $likeOrUnlike . "')";
}
mysqli_query($conn, $query);
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
comment-add.php
<?php
require_once ("db.php");
$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');
$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;
?>
get-like-unlike.php
<?php
require_once ("db.php");
$commentId = $_POST['comment_id'];
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
And my index.php code for posts and likes:
<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>
<font color="white"><input type="button" class="btn-submit" id="submitButton"
value="Publish" /></font>
</div>
</form>
</div>
<div id="output"></div>
<script>
var totalLikes = 0;
var totalUnlikes = 0;
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 + ')');
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'];
var obj = getLikesUnlikes(commentId);
if (parent == "0")
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
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 class='post-action'>\ " + like_icon + " \
<span id='likes_" + commentId + "'> " + totalLikes + " likes </span>\
</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++)
{
var obj = getLikesUnlikes(data[i].comment_id);
if (commentId == data[i].parent_comment_id)
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
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 class='post-action'> " + like_icon + " \
<span id='likes_" + data[i]['comment_id'] + "'> " + totalLikes + " likes </span>\
</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);
}
}
}
function getLikesUnlikes(commentId)
{
$.ajax({
type: 'POST',
async: false,
url: 'get-like-unlike.php',
data: {comment_id: commentId},
success: function (data)
{
totalLikes = data;
}
});
}
function likeOrDislike(comment_id,like_unlike)
{
$.ajax({
url: 'comment-like-unlike.php',
async: false,
type: 'post',
data: {comment_id:comment_id,like_unlike:like_unlike},
dataType: 'json',
success: function (data) {
$("#likes_"+comment_id).text(data + " likes");
if (like_unlike == 1) {
$("#like_" + comment_id).css("display", "none");
$("#unlike_" + comment_id).show();
}
if (like_unlike == -1) {
$("#unlike_" + comment_id).css("display", "none");
$("#like_" + comment_id).show();
}
},
error: function (data) {
alert("error : " + JSON.stringify(data));
}
});
}
</script>
comment-list.php
<?php
require_once ("db.php");
$memberId = 1;
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " 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);
?>
Im really looking forward for some help, ive been working on this script for a while and this is the last thing I need before launching, thanks in advice!
Here's a picture of a website, just to see how its working

You should write your query in comment-list.php like this
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY tbl_like_unlike.like_unlike DESC, tbl_comment.date DESC";
This will automatically sort your data to have comment with most likes on top and then sort by the newest date. So if a comment has the same amount of likes of another comment, the newest will show up on top.
COMMENT RESPONSE
You can do it in javascript like this:
for (var i = 0; i < data.length; i++) {
if(i == 0) {
//put comment at top of page
} else {
// Put comment in normal place
}
}

Related

Select2 Not active

<script>
$(document).ready(function(){
$("#btn-tambah-form").click(function(){
var jumlah = parseInt($("#jumlah-form").val());
var nextform = jumlah + 1;
$("#insert-form").append(
"<div class='row mb-10 p-10'>" +
" <div class='input-group col-md-2'>" +
" <?php $result = mysqli_query($conn, 'SELECT * FROM produk');?>" +
" <?php $jsArray = 'var idproduk = new Array();\n';?>" +
" <select class='form-control select2' id=\'idproduk"+nextform+"\' name=\'idproduk[]\' onchange=\'changeProduk"+nextform+"(this.value),sum();\' required>" +
" <option></option>" +
" <?php while ($row = mysqli_fetch_array($result)) {?>" +
" <?php echo '<option value=\'' . $row['idproduk'] . '\'>' . $row['produk_nama'] . '</option>';?>" +
" <?php$jsArray .= 'idproduk[\'' . $row['idproduk'] . '\'] = {harga_beli:\'' . addslashes($row['harga_beli']) . '\',produk_satuan:\'' . addslashes($row['produk_satuan']) . '\'};\n';?>" +
" <?php }?>" +
" </select>" +
" </div>" +
"</div>");
$("#jumlah-form").val(nextform);
});
$("#btn-reset-form").click(function(){
$("#insert-form").html("");
$("#jumlah-form").val("1");
});
});
</script>
can someone help me. why my select2 not active when i put them on javascript.
when i put them outside java they can run correct.
please help me how to solve this code.
There is problem with backslashed quotes, remove them. It should be all.
<select class='form-control select2' id='idproduk"+nextform+"' name='idproduk[]' onchange='changeProduk"+nextform+"(this.value),sum();' required>" +

Display most liked post on a page php

I written a script where users can post without signing up or logging in and recieve likes. Sumbitted posts are being displayed on a page and post with most likes is first, which is great, but I created a Most Liked section where I would like to display post with most likes.
comment-like-unlike.php
?php
require_once ("db.php");
$memberId = 1;
$commentId = $_POST['comment_id'];
$likeOrUnlike = 0;
if($_POST['like_unlike'] == 1)
{
$likeOrUnlike = $_POST['like_unlike'];
}
$sql = "SELECT * FROM tbl_like_unlike WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if (! empty($row))
{
$query = "UPDATE tbl_like_unlike SET like_unlike = " . $likeOrUnlike . " WHERE comment_id=" . $commentId . " and member_id=" . $memberId;
} else
{
$query = "INSERT INTO tbl_like_unlike(member_id,comment_id,like_unlike) VALUES ('" . $memberId . "','" . $commentId . "','" . $likeOrUnlike . "')";
}
mysqli_query($conn, $query);
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
comment-add.php
<?php
require_once ("db.php");
$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');
$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;
?>
get-like-unlike.php
<?php
require_once ("db.php");
$commentId = $_POST['comment_id'];
$totalLikes = "No ";
$likeQuery = "SELECT sum(like_unlike) AS likesCount FROM tbl_like_unlike WHERE comment_id=".$commentId;
$resultLikeQuery = mysqli_query($conn,$likeQuery);
$fetchLikes = mysqli_fetch_array($resultLikeQuery,MYSQLI_ASSOC);
if(isset($fetchLikes['likesCount'])) {
$totalLikes = $fetchLikes['likesCount'];
}
echo $totalLikes;
?>
comment-list.php
<?php
require_once ("db.php");
$memberId = 1;
$sql = "SELECT tbl_comment.*,tbl_like_unlike.like_unlike FROM tbl_comment LEFT JOIN tbl_like_unlike ON tbl_comment.comment_id = tbl_like_unlike.comment_id AND member_id = " . $memberId . " ORDER BY tbl_like_unlike.like_unlike DESC, tbl_like_unlike.date DESC";
$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);
?>
index.php:
<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>
<font color="white"><input type="button" class="btn-submit" id="submitButton"
value="Publish" /></font>
</div>
</form>
</div>
<div id="output"></div>
<script>
var totalLikes = 0;
var totalUnlikes = 0;
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 + ')');
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'];
var obj = getLikesUnlikes(commentId);
if (parent == "0")
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
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 class='post-action'>\ " + like_icon + " \
<span id='likes_" + commentId + "'> " + totalLikes + " likes </span>\
</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++)
{
var obj = getLikesUnlikes(data[i].comment_id);
if (commentId == data[i].parent_comment_id)
{
if(data[i]['like_unlike'] >= 1)
{
like_icon = "<img src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img style='display:none;' src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
else
{
like_icon = "<img style='display:none;' src='like.png' id='unlike_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",-1)' />";
like_icon += "<img src='unlike.png' id='like_" + data[i]['comment_id'] + "' class='like-unlike' onClick='likeOrDislike(" + data[i]['comment_id'] + ",1)' />";
}
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 class='post-action'> " + like_icon + " \
<span id='likes_" + data[i]['comment_id'] + "'> " + totalLikes + " likes </span>\
</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);
}
}
}
function getLikesUnlikes(commentId)
{
$.ajax({
type: 'POST',
async: false,
url: 'get-like-unlike.php',
data: {comment_id: commentId},
success: function (data)
{
totalLikes = data;
}
});
}
function likeOrDislike(comment_id,like_unlike)
{
$.ajax({
url: 'comment-like-unlike.php',
async: false,
type: 'post',
data: {comment_id:comment_id,like_unlike:like_unlike},
dataType: 'json',
success: function (data) {
$("#likes_"+comment_id).text(data + " likes");
if (like_unlike == 1) {
$("#like_" + comment_id).css("display", "none");
$("#unlike_" + comment_id).show();
}
if (like_unlike == -1) {
$("#unlike_" + comment_id).css("display", "none");
$("#like_" + comment_id).show();
}
},
error: function (data) {
alert("error : " + JSON.stringify(data));
}
});
}
</script>
I will post picture of a website just you guys have a clue what Im talking about:
This is where I want most liked post:
SELECT posts from your_table ORDER BY likes DESC

dynamic form fields with javascript an php: It doesn't work

I have a small javascript which add form-fields dynamically.
My javascript snippet without any php codes works fine.
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />' );
});
});
</script>
But in this script i need an array that read entries from a database for a select option field (dropdown).
I do it like this:
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]' + '">
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
</select><br />'
);
});
});
</script>
It doesn't work. I get the following error
Uncaught SyntaxError: Unexpected token ILLEGAL
What's wrong? Iam very glad for any help.
Regards,
Stefan
You can try this :
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Artikel ' + counter + '</strong><br />'
+ '<input id="field1_' + counter + '" name="dynfields[]' + '" type="text" class="login-username" /><br />'
+ '<input id="field2_' + counter + '" name="dynfields2[]' + '" type="text" class="login-username" /><br />'
+ '<select name="dynfields3[]">' +
+ '<?php $abfrage = "SELECT * FROM artikel"; mysql_query("SET NAMES SET 'utf8'"); $ergebnis = mysql_query($abfrage); while($row = mysql_fetch_object($ergebnis)){?>'
+ '<option value="' + '<?php echo $row->id ?>' + '">' + '<?php echo $row->name ?>' + '</option>'
+ '<?php }?></select></br>'
);
});
});
</script>
I think the error is here
+ '<select name="dynfields3[]' + '">
maybe you intend
+ '<select name="dynfields3[]" >' +
<?php
$abfrage = "SELECT * FROM artikel";
mysql_query("SET NAMES SET 'utf8'");
$ergebnis = mysql_query($abfrage);
while($row = mysql_fetch_object($ergebnis))
{
$id = $row->id;
$name = $row->name;
$beschreibung = $row->beschreibung;
$preis = $row->preis;
echo " <option value='$row->id'>$row->name;</option> ";
}
?>
+ '</select><br />';

jQuery not pushing JSON-data

I have the following script which is supposed to pull data and display it in a HTML table:
$('#search_filter_button').click(function (e) {
e.preventDefault(); // Stop form submission
var county = $('#filter_county').val(),
kp_type = $('#filter_kp_type').val(),
getUrl = window.location,
baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
html_tr = '';
$.ajax({
type: 'GET',
url: baseUrl + "/reports/get_report.php?county=" + county + "&kp_type=" + kp_type,
dataType: "JSON",
success: function (data) {
console.log(data);
for (i = 0; i < data.length; i++) {
html_tr += '<tr>\n\
<td>' + data[i].name + '</td>\n\
<td>' + data[i].Abbrv + '</td>\n\\n\
<td>' + data[i].partner_name + '</td>\n\\n\
<td>' + data[i].facility_name + '</td>\n\\n\
<td>' + data[i].county + '</td>\n\\n\
<td>' + data[i].no_kps + '</td>\n\\n\
<td>' + data[i].activity_stamp + '</td>\n\</tr>';
}
$('#tbody_append').empty();
$('#tbody_append').append(html_tr);
}, error: function (data) {
}
});
});
My get_report.php file looks like this:
include '../database/db_connect.php';
$mysqli = mysqli_connect($host_name, $user_name, $password, $database);
$county = $_GET['county'];
$kp_type = $_GET['kp_type'];
// get the records from the database
$result = mysqli_query($mysqli, "SELECT * FROM `no_individaul_kps_contacted` where county='$county'");
$count_row = mysqli_num_rows($result);
if ($count_row >= 1) {
// display records if there are records to display
while ($user_data = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo json_encode($user_data);
}
} else {
// show an error if there is an issue with the database query
echo "Error: " . $mysqli->error;
}
// close database connection
mysqli_close($mysqli);
This pulls the information and echoes it back in JSON ENCODE format. But my JavaScript is not returning a success.
Please advise what am I doing wrong.
Collect the user data into array inside the while loop and move json_encode($data) outside the while loop:
$select = "SELECT * FROM `no_individaul_kps_contacted` where county='$county'";
$result = mysqli_query($mysqli, $select);
$data = [];
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
}
echo json_encode($data);

How to add form elements using javascript that contains php?

This is my code:
Category:
<select name='category'>
<?php
$query = "SELECT * FROM `categories`";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
echo "<option name={$row[0]} value={$row[1]}>{$row[1]}</option>";
}} ?>
</select> <br><br>
Quantity:
<input type='text' name='quantity' onkeypress="return isNumberKey(event)"><br><br>
Price:
<input type='text' name='price' onkeypress="return isNumberKey(event)"><br><br>
Insert another item
<input type='submit' value='Submit'>
When user clicks on Insert another item, I want to again add Category, Quantity and Price as seen above using Javascript.
Please help.
Just a quick solution without the need of an AJAX request.
<?php
$categories = array();
$query = "SELECT * FROM `categories`";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
$categories[$row[0]] = $row[1];
}
}
?>
<div id="groups"></div>
Insert another item
<script>
var categories = <?= json_encode($categories) ?>,
groupId = 0;
$(function() {
insertGroup();
$('#insert-another-item').on('click', function() {
insertGroup();
return false;
});
});
function insertGroup() {
group = '<div class="group">'
+ '<select name="groups[' + groupId + '][category]"></select>'
+ '<input type="text" name="groups[' + groupId + '][quantity]">'
+ '<input type="text" name="groups[' + groupId + '][price]">'
+ '</div>';
$('#groups').append(group);
$.each(categories, function(key, value) {
$('select[name="groups[' + groupId + '][category]"]').append('<option value="' + key + '">' + value + '</option>');
});
groupId++;
}

Categories

Resources