Populating a HTML table using JQUERY, PHP and AJAX - javascript

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;

Related

How to display MediumBLOB from MySQL database using Javascript

So I am trying to display the information that I have retrieved from a database and I'm using Javascript to pass these info to their corresponding tags using the IDs. I have no problem with outputting the text, but I am having a hard time to output the images in the database which is a MediumBLOB.
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var buffer = new Buffer(userid.images);
var bufferBase64 = buffer.toString('base64');
$('#img').attr("src", "data:image/jpeg;base64," + bufferBase)
});
$('#viewModal').modal("show");
}
As for the update.php, here is the condition that receives the Post method.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'phpfinals');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ".$conn->connect_error);
}
//Sending details to be viewed
if(isset($_POST['sendview']))
{
$user_id = $_POST['sendview'];
$stmnt = mysqli_query($conn,"SELECT `username`, `password`, `firstname`, `middlename`, `lastname` , `gender`, `yearlevel`, `position`, `accesslevel`, `images` FROM phpfinals.records WHERE `username` = $user_id");
$result=array();
while($row = mysqli_fetch_assoc($stmnt))
{
$result = $row;
}
echo json_encode($result);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid or data not found";
}
?>
try creating an URL object
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var objectURL = URL.createObjectURL(userid.images);
$('#img').attr("src", objectURL)
});
$('#viewModal').modal("show");
}
and as a suggestion not related to your question instead of echo should be better use return for send the result
return json_encode($result);

how to append data using ajax posts and datatables are not working?

Hello there am trying to get the data from database using ajax posts but i didn't get any data properly. first column data is splinting in another columns(Member names are coming in image field and info field). Image also shared please check that. And also datatables are not working while fetching the data using Ajax. Help me out from this problem...
Thanks & Regards
<body>
<label>Party</label>
<select id='partydropdown' name='partydropdown' onchange="partyFunction();">
<option>--select a party--</option>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row["Id"];?>">
<?php echo $row["PartyName"];?>
</option>
<?php }}?>
</select>
<div id="showhide"></div>
</body>
<script type="text/javascript">
function partyFunction(){
debugger;
$("#showhide").empty();
$("#showhide").html('');
$("#showhide").append("<table class='table table-bordered text-center table-responsive' border='1px' id='example'>"+
"<tr>"+
"<th>PartyMemberName</th>"+
"<th>Image</th>"+
"<th>Info</th>"+
"</tr>"+
"<tbody id='partyBody'>"+
"</tbody>"+
"</table>"
);
$postdata = {};
$postdata["Id"]=$("#partydropdown").val();
console.log($("#partydropdown").val());
$.post('test_data.php',$postdata,function (data) {
debugger;
console.log(data);
console.log(data["data"][0].candiateName);
$("#partyBody").empty();
$("#partyBody").html('');
console.log(data["data"]);
console.log(data["data"].length);
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
$("#partyBody").append("<tr>"+
"<td id='resdata"+i+"'></td>"+
"<td id='resdata1"+i+"' ></td>"+
"<td id='resdata2"+i+"'></td>"+
"</tr>");
$("#resdata"+i).text(data["data"][i].candiateName);
$("#resdata1"+i).append("<img id='photo"+i+"'>");
$("#resdata2"+i).text(data["data"][i].Background);
$("#photo"+i).attr('src', 'http://aptsvotes.com/wp-content/themes/apts2019/img'+data["data"][i].Photo );
}
}
});
};
</script>
here is the test_data.php code
<?php
include_once "conn.php";
include_once "voterdbclass.php";
session_start();
$tbl_name2="Parties";
$dbObj = new Database1();
$values1 = array("all");
$querys = "SELECT c1.CandidateName,c1.Photo,c1.Background ,c1.Type FROM aptsv1_votes.Parties p1 LEFT JOIN aptsv1_votes.Candidates c1 ON c1.CurrentPartyId = p1.Id where p1.Id ='" . $_POST['Id'] . "' limit 21";
$res = $dbObj->SelectRecord($tbl_name2,$values1,"","$querys");
$data=array();
$i=0;
while ($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data[$i]['candiateName']=$rs['CandidateName'];
$data[$i]['Photo']=$rs['Photo'];
$data[$i]['Background']=$rs['Background'];
$i++;
}
$json_array= array(
"data" =>$data
);
echo json_encode($json_array);
?>
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
var imge = data["data"][i].Photo;
var name = data["data"][i].candiateName;
var bg = data["data"][i].Background;
$("#partyBody").append("<tr>"+
"<td id='resdata" + i + "'>" + name+"</td>"+
"<td id='resdata1" + i + "' ><img id= 'photo" + i + "' src='http://aptsvotes.com/wp-content/themes/apts2019/img'" + imge+"></td>"+
"<td id='resdata2" + i + "'>" + bg+"</td>"+
"</tr>");
}
}
You have to parse JSON data into the first script. While ajax result you posting with json_encode, I found missing
var data = $.parseJSON(data);
console.log(data["data"].length);
into code
$.post('test_data.php',$postdata,function (data) {
// debugger;
console.log(data);
var data = $.parseJSON(data); // Add this line in your code and verify
console.log(data["data"].length);
Thank you!

How to add data from database into object in php for temporary using while loading

I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'

Clear previous return data from DataBase in HTML using PHP+JSON+AJAX

I am doing Database project and I built Database and UI, the communication between the DB and the UI is made by PHP,JSON and AJAX.
In the Top 3 tab I am trying to bring the top 3 student with the highest grades, my plan was to use a dropdown options and pick each time another course and bring the top 3 each time. The code is working but not as I wanted.
It is always append the new results to the last results. If I am trying to bring another top 3 student it is append the new results to the last results and not clearing the previous data.
My code is :
Javascript:
$('#showCourse').click(function(){
console.log("showCourse");
var top3 = $('#top3').val();
var top3Table = $('#top3Table');
console.log(top3);
$.ajax({
type: "POST",
dataType:"json",
data: {"top3" : top3},
url: "jsonTop3.php",
cache: false,
success: function(data){
console.log("success");
console.log(data.length);
for (var i = 0; i < data.length; i++) {
var row = "<tr><td>" + data[i].student_id + "</td>" +
"<td>" + data[i].grade + "</td></tr>";
top3Table.append(row);
}
}
});
});
HTML:
<div class="container">
<div class="insertData" style="height:180px;">
<h3>Pick Course name:</h3>
<form class="form-horizontal">
<select class="form-control" id="top3" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option>None</option>
<option>Operational Systems</option>
<option>Integrators</option>
<option>Web Development</option>
<option>Algebra</option>
<option>Chimestry</option>
<option>Biology</option>
<option>History</option>
<option>JAVA</option>
<option>Intro to Math</option>
<option>UNIX</option>
</select>
<input type="hidden" name="hid" id="text_content" value="">
</form>
<div class="rightButtons">
<button type="add" name="type" class="btn btn-success" id="showCourse">Show</button>
</div>
</div>
<div class="table">
<h2>Top 3 Table</h2>
<table class="table table-striped">
<thead>
</thead>
<tbody id = "top3Table">
</tbody>
</table>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
PHP:
<?php
function printStudents() {
$host="127.0.0.1";
$port=3306;
$user="root";
$password="root";
$dbname="courcessystem";
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$sql = "SELECT * FROM reg_courses
ORDER BY course_id ASC";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));
$emparray = array();
while($row =mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$con->close();
}
printStudents();
?>
use
success: function(data){
var row = '';
for (var i = 0; i < data.length; i++) {
row += "<tr><td>" + data[i].student_id + "</td>" +
"<td>" + data[i].grade + "</td></tr>";
}
top3Table.html(row);
}
instead of your success function
What about empty the table before appending rows?
$.ajax({
type: "POST",
dataType:"json",
data: {"top3" : top3},
url: "jsonTop3.php",
cache: false,
success: function(data){
console.log("success");
console.log(data.length);
top3Table.empty();
for (var i = 0; i < data.length; i++) {
var row = "<tr><td>" + data[i].student_id + "</td>" +
"<td>" + data[i].grade + "</td></tr>";
top3Table.append(row);
}
}

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