Print sql table with JSON - php

I want to print all sql table and show them in html table. I am new in php, JSON and AJAX. I send username successfully and get result in php. I think there is a problem in JSON part or AJAX. Can anyone help me?
index.php
<div class="col-lg-6">
<p id="usr" style="color:gray; font-size: 48px;"></p>
<script type="text/javascript">
var usr = document.getElementById("dom-target");
var username = usr.textContent;
username = username.trim().replace(/ /g, '%20');
document.getElementById("usr").innerHTML = username;
var sendtophp = "username="+username;
$.ajax({
type: "POST",
url: "getcoursetable.php",
data: sendtophp,
dataType:"json",
success: function(response) {
console.log(response);
var trhtml ='';
document.getElementById("demo").innerHTML = response;
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.cname + '</td><td>' + item.subject + '</td><td>' + item.course + '</td><td>'+ item.grade + '</td></tr>';
});
$('#results').append(trHTML);
}
});
</script>
<table id="results"></table>
</div>
getcoursetable.php
<?php
include_once "connection.php";
if(isset($_POST["username"])){
$nick = $_POST["username"];
$prep = "SELECT * FROM `enrolledtable` WHERE nickname='$nick'";
$results = mysqli_query($con, $prep);
$jsonData = array();
while ($row = $results->fetch_row()) {
$jsonData[] = $row;
}
echo json_encode($jsonData);
}
?>
Now, I can print data but not like a table, like that
<p id="demo">denemee,CS,300,B,denemee,CS,301,B ,denemee,CS,305,B ,denemee,CS,307,B,denemee,CS,408,A-,denemee,IE,208,B ,denemee,MATH,306,B</p>

your ajax function is looking for data of type json so you need to declare this at the top of getcoursetable.php
header('Content-Type: application/json');

The problem might sit around here :
console.log(response);
var trhtml ='';
document.getElementById("demo").innerHTML = response;
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.cname + '</td><td>' + item.subject + '</td><td>' + item.course + '</td><td>'+ item.grade + '</td></tr>';
});
$('#results').append(trHTML);
First, JavaScript is a Case Sensitive language : trhtml and trHTML are not the same variables.
Second, if your sentence "output of php" means you reported the output of console.log(), then response look like a string to me, you must make it parsed as Json.
Moreover, I don't know what the beginning of the string denemee is but it breaks the Json notation.

I solve my problem. This can take table in php and create html table.
index.php
<div class="col-lg-6">
<p id="usr" style="color:gray; font-size: 48px;"></p>
<script type="text/javascript">
var usr = document.getElementById("dom-target");
var username = usr.textContent;
username = username.trim().replace(/ /g, '%20');
document.getElementById("usr").innerHTML = username;
var sendtophp = "username="+username;
$.ajax({
type: "POST",
url: "getcoursetable.php",
data: sendtophp,
dataType:"json",
success: function(response) {
var trhtml ='';
$.each(response, function (i, item) {
trhtml += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td><td>'+ item[2] + '</td></tr>';
});
$('.append').append(trhtml);
}
});
</script>
<table id="results">
<tr>
<th>Name</th>
<th>Subject</th>
<th>Course</th>
<th>Grade</th>
</tr>
<tbody class="append">
</tbody>
</table>
</div>
getcoursetable.php
<?php
header('Content-Type: application/json');
include_once "connection.php";
if(isset($_POST["username"])){
$nick = $_POST["username"];
$prep = "SELECT subject,course,grade FROM `enrolledtable` WHERE nickname='$nick'";
$results = mysqli_query($con, $prep);
$jsonData = array();
while ($row = $results->fetch_row()) {
$jsonData[] = $row;
}
echo json_encode($jsonData);
}
?>

Related

Can not retrieve data json from the server using ajax on cordova

I tried to call / search data by ID , from the server using ajax in cordova , but when I click to display the data " undefined" , what's wrong ???
This my html
<input type="text" id="result" value=""/>
<button>get</button>
<div id="result2"></div>
function get (){
var qrcode = document.getElementById ("result").value;
var dataString="qrcode="+qrcode;
$.ajax({
type: "GET",
url: "http://localhost/book/find.php",
crossDomain: true,
cache: false,
data: dataString,
success: function(result){
var result=$.parseJSON(result);
$.each(result, function(i, element){
var id_code=element.id_code;
var qrcode=element.qrcode;
var judul=element.judul;
var hasil2 =
"QR Code: " + qrcode + "<br>" +
"Judul: " + Judul;
document.getElementById("result2").innerHTML = hasil2;
});
}
});
}
This my script on server
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =$row['qrcode'];
$array[] =$row['judul'];
$array[] =$row['jilid'];
}
echo json_encode($array);
}
try to change your parameter in calling ajax
var dataString = {qrcode : qrcode };
Change your php code as below
include "db.php";
$qrcode= $_GET['qrcode'];
$array = array();
$result=mysql_query("select * from book WHERE qrcode LIKE '%{$qrcode}%'");
while ($row = mysql_fetch_array($result)) { //fetch the result from query into an array
{
$array[] =['qrcode'=>$row['qrcode'],'judul'=>$row['judul'],'id_code'=>$row['jilid']];
}
echo json_encode($array);
}
RESOLVED the problem is. I try to replace with this script and the result was the same as I expected.
while ($row = mysql_fetch_object($result)){
$array[]=$row++;
}
echo json_encode($array);

Populate HTML table from AJAX response

I have some data in MySQL database. I want to show that data in html table based on the parameter selected by the user.
Following is the input section (HTML)
<form class="form-inline">
<div class="input-group">
<div>Enter Person Name</div>
<input class="form-control" id="tags">
</div>
<div class="btn-group">
<button type="submit" id="btnSubmit">Search</button>
</div>
</form>
This is the table where I want to populate the data coming from AJAX response.
<div class="dataTable_wrapper">
<table class='table table-striped table-bordered table-hover' id='records_table'>
<tr class='odd gradeX'>
<th>Name</th>
<th>Group</th>
<th>Work</th>
<th>Grade1</th>
<th>Grade2</th>
<th>Grade3</th>
<th>TeacherName</th>
<th>RollNo</th>
</tr>
</table>
</div>
Now on clicking the 'Search' button, I want to send the name to PHP file, and get the information form database.
for which I have done this:
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var selText = $('#tags').val();
if (selText === '') {
alert("Please select a name!");
} else {
$.ajax({
type: 'GET',
url: 'getData.php',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
jsonp: false,
data: {
q: selText
},
success: function (response) {
alert(response);
var trHTML = '';
$.each(response, function (i, item) {
$.each(item, function (_, o) {
trHTML += '<tr><td>' + o.Name +
'</td><td>' + o.Group +
'</td><td>' + o.Work +
'</td><td>' + o.Grade1 +
'</td><td>' + o.Grade2 +
'</td><td>' + o.Grade3 +
'</td><td>' + o.TeacherName +
'</td><td>' + o.RollNo. +
'</td></tr>';
});
});
$('#records_table').append(trHTML);
},
error: function (e) {
$("#txtHint").html(e.responseText);
}
});
}
});
});
The PHP code is
<?php
$servername = "localhost"; $username = "root"; $password = "21343"; $dbname = "do_demob";
$selectedName = $_GET['q'];
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT *** Don't have rights to reveal";
$result = mysqli_query($conn, $sql);
$rows = array();
if($result) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
}else {
echo 'MySQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($conn);
?>
The AJAX response is
[{"Name":"Sagar Mujumbdar","Group":"","TeacherName":"John Cena","RollNo":"SX51998","Work":"Sales","Grade1":"Good","Grade2":"5","Grade3":"1"}]
the Status Code is:200 OK. I also checked in Developer Tools' Network section, the data is coming completely and in correct format. The key names are also correct.
But unfortunately the data is not being displayed in the table.
Is the reason that because JSON object contain null values it is not displaying?
If not, then what else can be the reason?
You have a syntax error right after RollNo:
'</td><td>' + o.RollNo. +
Remove the ..
In your iteration, you go one element to deep, o.* will be undefined, because o already is "Sagar Mujumbdar", "", etc. One .each is enough:
$.each(response, function (i, o) {
trHTML += '<tr><td>' + o.Name +
'</td><td>' + o.Group +
'</td><td>' + o.Work +
'</td><td>' + o.Grade1 +
'</td><td>' + o.Grade2 +
'</td><td>' + o.Grade3 +
'</td><td>' + o.TeacherName +
'</td><td>' + o.RollNo. +
'</td></tr>';
});
I also created a fiddle with your AJAX response.
Try following logic. There may some error like braces, and comma because i edited it in here. try the table heading is also in javascript. I done it below. Please check
$(document).ready(function () {
$("#btnSubmit").click(function (e) {
e.preventDefault();
var selText = $('#tags').val();
if (selText === '') {
alert("Please select a name!");
} else {
$.ajax({
type: 'GET',
url: 'getData.php',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
jsonp: false,
data: {
q: selText
},
success: function (response) {
alert(response);
var trHTML = "<table class='table table-striped table-bordered table-hover' id='records_table'>
<tr class='odd gradeX'>
<th>Name</th>
<th>Group</th>
<th>Work</th>
<th>Grade1</th>
<th>Grade2</th>
<th>Grade3</th>
<th>TeacherName</th>
<th>RollNo</th>
</tr>";
for(var i =0;i < response.length-1;i++)
{
var o= response[i];
trHTML += '<tr><td>' + o.Name +
'</td><td>' + o.Group +
'</td><td>' + o.Work +
'</td><td>' + o.Grade1 +
'</td><td>' + o.Grade2 +
'</td><td>' + o.Grade3 +
'</td><td>' + o.TeacherName +
'</td><td>' + o.RollNo +
'</td></tr>';
}
trHTML+="</table>"
$('#records_table').append(trHTML);
},
error: function (e) {
$("#txtHint").html(e.responseText);
}
});
}
});
});

How get AJAX to Post JSON data into div

I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});

comment bar mysql php and ajax

I am trying to create a simple comment bar using PHP, AJAX, MySQL and json coding.
I've got two files written in php, the first one being a controller with a following code:
<?php
require("../includes/config.php");
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$comments = query("SELECT comments.comment, comments.author, comments.time FROM comments WHERE workid = ?", $_GET["workid"]);
echo json_encode($comments);
}
else if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_SESSION["userid"])) {
throw new Exception("Login");
}
else {
$result = query("INSERT INTO comments (comment, author, time, workid) VALUES(?, ?, ?, ?)", $_POST["text"], $_SESSION["userid"], date("Y-m-d H-i-s"), $_POST["workid"]);
if ($result !== false) {
echo "success";
}
}
}
?>
The second one is purported to display the records from MySQL, based on the data from the controller:
<script>
//loads the comments
$(document).ready(function(){
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.comment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
});
</script>
<script>
$(document).ready(function(){
$("#comment-button").click(function(){
$.ajax({
type: "POST",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>,
text: $("#comment-textarea").val()
},
dataType: "text",
success: function(e) {
var comment;
$.ajax({
type: "GET",
url: "../html/comments.php",
data: {
workid: <?php echo $id;?>
},
dataType: "json",
success: function(e) {
var lis = "";
for (var i = 0; i < e.length; i++) {
comment = e[i];
lis +=
"<li class='comment'>" +
"<div class='well'>" +
"<p>" +
"<a class='username' href='#'>" + comments.author + ": " + "</a>" +
comments.domment +
"</p>" +
"<small class='pull-right'>" + comments.time + "</small>" +
"</div>" +
"</li>";
}
$("#comments").html(lis);
$("#comment-textarea").val("");
},
error: function(e) {
$("#comments").html(
"<li class='comment'> Couldn't load comments </li>"
);
}
});
}
});
});
});
</script>
Everything works pretty fine, except of the final step; when displaying the data from the database, the only thing displayed is a statement 'undefined' instead of the corect data. Except of this, the amount of comments and form display correctly. I am using a Apache server with a php installed.
In your JavaScript code, you need to replace comments.<xxx> with comment.<xxx>, since comments is indeed an undefined object in your JaveScript.

Jquery Ajax Each function returns double

I have a Jquery Function that basically retrieves a list of users from the data base and inserts the information into divs. The problem is that im getting double reults, this is my first time retrieving from the database, Ive only ever sent to the database.. Any Help will be Greatly appreciated.
Thanks :)
Heres the Jquery Code:
$(function () {
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var mobile = row[2];
var address = row[3];
var email = row[4];
$.each(rows, function() {
$('#contain').append('<div id="name">' + '<span>' + name + '</span>' + '</div>' + '<div id="id">' + id + '</div>' + '<div id="mobile">' + mobile + '</div>' + '<div id="address">' + address + '</div>' + '<div id="email">' + email + '</div>');
});
}
}
});
});
and the PHP:
$result = mysql_query("SELECT * FROM $tableName");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
I think the problem is here:
$.each(rows, function (){
$('#contain').append('<div id="name">'+'<span>'+name+'</span>'+'</div>'+'<div id="id">'+id+'</div>'+'<div id="mobile">'+mobile+'</div>'+'<div id="address">'+address+'</div>'+'<div id="email">'+email+'</div>');
});
you should do just
$('#contain').append('<div id="name"><span>'+name+'</span></div><div id="id">'+id+'</div><div id="mobile">'+mobile+'</div><div id="address">'+address+'</div><div id="email">'+email+'</div>');

Categories