jQuery not pushing JSON-data - javascript

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

Related

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

Count like and unlike php

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

How to clear last generated table with new one on radio select

I am working on a module with 3 radio buttons. Clicking one radio button lists data related to it and so on. I have applied ajax call on radio buttons click and return an array in the response. My problem here is for each radio button click the data keeps on adding into the list. For e.g. if I click on 'All users' radio it displays the data related to "All" but again if I click on "Unapproved Users" radio, the list adds up to the 'All users ' listing at the bottom. So how can I reset the $_POST variable each time the data is rendered so that new list appears for new radio selection, I would really appreciate the help or advice for this.
<script>
$('#selection').change
(
function()
{
var selected_value = $("input[name='users']:checked").val();
//till here the code works fine.
$.ajax
(
{
url: "approval_ajax.php",
dataType : "json",
type: "POST",
cache: false,
data: { selected_value : selected_value },
success: function(response)
{
console.log(response);
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var email = response[i].email;
var employee_id = response[i].employee_id;
var first_name = response[i].first_name;
var middle_name = response[i].middle_name;
var last_name = response[i].last_name;
var mobile = response[i].mobile;
var created_on = response[i].created_on;
var disabled = response[i].disabled;
var tr_str = "<tr>" +
"<td>" + (i+1) + "</td>" +
"<td>" + email + "</td>" +
"<td>" + employee_id + "</td>" +
"<td>" + first_name + " " + middle_name + " " + last_name + "</td>" +
"<td>" + mobile + "</td>" +
"<td>" + created_on + "</td>" +
"<td><input type='checkbox' name='check[]'" + disabled + "value= '" + id + "' class='checkbox' id='select_all' ></td>" +
"<input type='hidden' value='" + id + "' name='user_id' id='user_id' >" +
"</tr>";
$("#example").append(tr_str);
}
alert("AJAX was a success");
}
}
);
}
);
</script>
approval_ajax.php
session_start();
require("../includes/config.php");
require("../classes/Database.class.php");
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
$return_arr = array();
$status='';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$value = filter_input(INPUT_POST, "selected_value");
if (isset($value))
{
$users=$value;
}else{
$users='';
}
switch ($users)
{
case "all":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3";
break;
case "approved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =1";
break;
case "unapproved":
$sqlQuery = "SELECT * FROM tbl_user WHERE type =3 AND status =0";
break;
}
$sq = $db->query($sqlQuery);
if ($db->affected_rows > 0) {
while ($row = mysql_fetch_array($sq)) {
$disabled = '';
if ($status == '1') {
$disabled = "disabled = 'disabled' checked='checked' ";
}
$id = $row['id'];
$email = $row['email'];
$employee_id = $row['employee_id'];
$first_name = $row['first_name'];
$middle_name = $row['middle_name'];
$last_name = $row['last_name'];
$mobile = $row['mobile'];
$created_on1 = $row['created_on'];
$created_on = date("d-m-Y", strtotime($created_on1));
$return_arr[] = array("id" => $id,
"email" => $email,
"employee_id" => $employee_id,
"first_name" => $first_name,
"middle_name" => $middle_name,
"last_name" => $last_name,
"mobile" => $mobile,
"created_on" => $created_on,
"disabled" => $disabled
);
}
}
header('Content-Type: application/json', true, 200);
echo json_encode($return_arr);
}
An append() jQuery function adds html content to requested element. In your case, you want to refresh users list on click of radio select. You need to use html() jQuery function to clear old result and add new result to requested element.
So please modify following line of your code:
$("#example").append(tr_str);
to
$("#example").html(tr_str);
Let me know if it helps.

CSV download with PHP/jQuery

I'm trying to develop a way for users to download a table in CSV format via jQuery/PHP.
My aim is to send the jQuery request to the server using PHP.
PHP then creates the CSV content and returns it.
jQuery then forces the browser to download the content as a CSV file.
I've got 90% working, the last bit is that I need to force the CSV download in the users browser using jQuery.
My PHP script
<?php
class Export {
public static function tocsv($results = array(), $fields = array(), $filename) {
$fh = fopen('php://output', 'w');
ob_start();
fputcsv($fh, $fields);
if(!empty($results)) {
foreach($results as $row) {
fputcsv($fh, (array) $row);
}
}
$string = ob_get_clean();
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$filename");
exit($string);
}
}
?>
My jQuery script
$(function() {
var btnName;
$('.button').click(function() {
btnName = $(this).attr('name');
btnValue = $(this).attr('value');
});
$("#spendReports").submit(function(event) {
event.preventDefault();
var formData = $('#spendReports').serializeArray();
formData.push({ name: btnName, value: btnValue });
$.post('spendReports.php', formData, function(data)
{
var data = $.parseJSON(data);
$.each(data, function(i, val) {
var newRow = '<tr><td class="dates-col" data-th="Date">' + data[i]["dates"] + '</td><td data-th="Project name">' + data[i]["project"] + '</td><td data-th="Total budget">' + data[i]["budget"] + '</td><td data-th="Plot numbers">' + data[i]["plots"] + '</td><td data-th="Categories">' + data[i]["categories"] + '</td><td data-th="Day work spent">£' + data[i]["day_work_spent"] + '</td><td data-th="% spend">' + data[i]["day_work_spent_percent"] + '%</td><td data-th="Price work spent">£' + data[i]["price_work_spent"] + '</td><td data-th="% spend">' + data[i]["price_work_spent_percent"] + '%</td><td data-th="Agency work spent">' + data[i]["agency_work_spent"] + '</td><td data-th="% spend">' + data[i]["agency_work_spent_percent"] + '%</td><td data-th="Subcon spent">' + data[i]["subcon_work_spent"] + '</td><td data-th="% spend">' + data[i]["subcon_work_spent_percent"] + '%</td><td data-th="Supervision spent">' + data[i]["supervision_spent"] + '</td><td data-th="% spend">' + data[i]["supervision_work_spent_percent"] + '%</td><td data-th="Total spent">£' + data[i]["total_spent"] + '</td></tr>';
$("#results > tbody").append(newRow);
});
});
});
});
This is different from Download File Using jQuery as i'm not physically creating a file on the server and therefore do not have a phsical link to send to jQuery.
Have a look at this answer: https://stackoverflow.com/a/4551467/563802
In your case it should be something like this:
var uriContent = "data:text/csv," + encodeURIComponent(data);
newWindow=window.open(uriContent, 'newDocument');

how checking multiple field using ajax & mysql

how to check multiple field using ajax & mysql
for example, I Want to check or validate if an email exist in my database
my code is
jquery_append.js
$(document).ready(function() {
var count = 0;
$("#add_btn").click(function(){
count += 1;
$('#container').append(
'<div class="s"><tr class="records">'
+ '<td ><div id="'+count+'">No : ' + count + '</div></td></tr>'
+ '<tr class="records"><td><label>Email</label><input id="email_' + count + '" name="email_' + count + '" type="text" class="email" required><label>Nama Depan</label><input id="nama_depan_' + count + '" name="nama_depan_' + count + '" type="text"><label>Nama Belakang</label><input id="nama_belakang_' + count + '" name="nama_belakang_' + count + '" type="text"></td></tr>'
+ '<tr class="records"><td><label>Tipe Operasi</label><select name="tipe_operasi_' + count + '"><option value="0">-Pilih-</option></select></td><tr>'
+ '<tr class="records"><td><label>Lokasi</label><select name="lokasi_' + count + '"><option value="0">-Pilih-</option></select></td><tr>'
+ '<tr class="records"><td><label>Alamat</label><input id="alamat_' + count + '" name="alamat_' + count + '" type="text"></td><tr>'
+ '<br><tr class="records"><td><a class="remove_item" href="#" >Delete</a>'
+ '<input id="rows_' + count + '" name="rows[]" value="'+ count +'" type="hidden"></td></tr><tr><td><hr></td></tr></div>'
);
});
$(".remove_item").live('click', function (ev) {
if (ev.type == 'click') {
$(this).parents(".s").fadeOut();
$(this).parents(".s").remove();
}
});
});
Write a function and trigger it on blur of your email field. Pass your email as a parameter of your function and check it into your database.
This is your email field:
<input type="text" class="form-control" name="email" id="email" value="" />
This is your JavaScript code:
$(document).ready(function() {
$("#email").blur(function(){
var email = $("#email").val();
if(email != ""){
$.ajax({
url: 'ajax_function_url',
data: {email:email},
type: 'post',
complete: function(output) {
var isExist = output.responseText;
if(isExist === '1'){
alert('This email is already in use.');
}else{
alert('success!!');
}
}
});
}else{
alert('Email should not be empty');
}
});
}
This is your PHP function which is called by Ajax:
function CheckEmailExist() {
$conn = new mysqli($servername, $username, $password, $dbname);
if (isset($_POST['email']) && $_POST['email'] != "") {
$sql = "SELECT id FROM `table` WHERE `email` = '" . $_POST['email'] . "'";
$result = $conn->query($sql);
echo mysql_num_rows($result);
}
exit();
}
This way you can check if your data exists in your database or not via ajax.

Categories

Resources