AJAX not functioning - php

I have been staring at this for literally two hours trying to fix it. Any help would be appreciated. For some reason the table isn't being loaded when the button is clicked.
Here's the relevant part of my head:
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
</head>
This is my table:
<div class="container">
<div class="midtxt">
<div id = "transactions-sav" style="margin-top: 0;">
<h2>Most Recent Transactions</h2>
<table>
<thead>
<tr>
<th>Username</th>
<th>Amount</th>
<th>Time & Date</th>
<th>Account Type</th>
</tr>
</thead>
<tbody>
<div id="trans-div">
</div>
</tbody>
</table>
<hr />
</div>
</div>
<a class="btn light-blue waves-effect waves-light table-end" id="trans-more" style="margin-top: 35px;">Load More Transactions</a>
</div>
This is my Ajax transmitter:
<script>
$(document).ready(function() {
let transCount = 20;
$('#trans-more').on('click', function() {
transCount += 20;
console.log('click');
console.log(transCount);
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: <?php echo $_SESSION['user_id']; ?>}, function() {
console.log('callback');
});
});
console.log('test1');
});
</script>
This is my PHP script for generating the table. It is worth noting that initialize() starts a session.:
<?php
require_once 'dbc-stu.inc.php';
require_once 'initialize.inc.php';
require_once 'app/transactions/transhist.inc.php';
initialize();
initialize_secure();
//Import the count
$limit = $_POST['transNewCount'];
$userID = $_SESSION['user_id'];
$sql = "SELECT * FROM transactions WHERE trans_targetID ='$userID' ORDER BY trans_time DESC LIMIT $limit";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $key => $value) {
if ($key === 'trans_time') {
$time = $value;
date_default_timezone_set("America/Los_Angeles");
$time = date("F j, Y, g:i a",$time);
} elseif ($key === 'trans_amount') {
$amnt = $value;
} elseif ($key ==='trans_targetID') {
$username = idToUsername($value);
} elseif ($key === 'trans_accType') {
$accType = $value;
}
}
echo '<td>' . $username . '</td>';
echo '<td>' . $amnt . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $accType . '</td>';
echo '</tr>';
}
Edit, thanks a lot everybody. I'm fairly new to the web development community, so it's cool to see everyone help out!

Remove div tag from tag and add id in tbody attribute as below.
<tbody id="trans-div"></tbody>

Put the php code<?php echo $_SESSION['user_id']; ?> inside a <script> tag into double quote as it's causing the SyntaxError which break` your script code.
That's why you are not able to view XHR into console
Try the following:
$('#trans-div').load('includes/loadtranshistajax.inc.php', {transNewCount: transCount,user_id: "<?php echo $_SESSION['user_id']; ?>"}, function() {
console.log('callback');
});

Related

Query String PHP

I'm trying to get the Owner's details by clicking on their name from the table at the bottom.
<html>
<head>
<title>Home</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<h1>Welcome to Poppleton Dog Show! This year 50 owners entered 300 dogs in 10 events!</h1>
<?php
include './connection.php';
$sql = "SELECT owners.id AS id, owners.name AS Owner, owners.email AS Email, dogs.name AS Name, ROUND(avg(score), 1) AS avg_score, breeds.name AS breed_name, COUNT(entries.id) AS entries_count\n"
. "FROM entries\n"
. "JOIN dogs ON dogs.id = entries.dog_id\n"
. "JOIN breeds ON dogs.breed_id = breeds.id\n"
. "JOIN owners ON owners.id = dogs.owner_id\n"
. "GROUP BY dogs.id\n"
. "HAVING entries_count > 1\n"
. "ORDER BY `avg_score` DESC\n"
. "LIMIT 10";
$result = $conn->query($sql);
echo "<table '<td align='center'>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>". "" ."". $row['Owner']. "</td>";
echo "<td>". "" ."<a href= mailto:$row[Email]>$row[Email]</a></td>";
echo "<td>". "" . $row["Name"] . "</td>";
echo "<td>". "" . $row["breed_name"] . "</td>";
echo "<td>". "" . $row["avg_score"] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
<!-- connection message will fade away-->
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
my $_GET method on the other page is now taking the number but it's still not displaying the owner's details and no errors or anything. I don't know what's wrong with the code. A would appreciate any advice regarding code, formatting, etc.
<html>
<head>
<title>OwnerDetail</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<?php
include './connection.php';
?>
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "Data Error";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
echo " Success ";
$row = $count->fetch(PDO::FETCH_OBJ);
echo "<table>";
}
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>
";
echo "</table>";
?>
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
You really should consider doing this:
Replace the ancient jQuery
Simplify the PHP which is already producing invalid HTML
Ajax the data only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$("#ownerTable a.owner").on("click", function(e) {
e.preventDefault(); // stop link
const ownerDetails = $.get(this.href, function(data) {
$("#output").html(data)
});
});
});
<script>
and have
<table>
<thead>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>
</thead>
<tbody id="ownerTable">
<? while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td>
<a class="owner" href="OwnerDetails.php?id=<?= $row['id'] ?>"><?= $row['Owner'] ?></a>
</td>
<td>
<?= $row[Email] ?>
</td>
<td>
<?= $row["Name"] ?>
</td>
<td>
<?= $row["breed_name"] ?>
</td>
<td>
<?= $row["avg_score"] ?>
</td>
</tr>
<? } ?>
</tbody>
<tbody id="output"></tbody>
</table>
where Ownerdetails.php now looks like
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "<tr><td>Data Error</td></tr>";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>";
}
?>

Back button like in file browser

I am creating a document management system for my project. I just want to know if there is a possible way to achieve a back button like in the photo below.
see the photo here
Here is my code for the document management system:
index.php
<main class="page-content">
<div class="container-fluid">
<div class="breadcrumb">
<div class="item"> Document</div>
</div>
<div class="load-data">
<?php
require_once 'config.php';
$sql = "SELECT * FROM tbl_menu WHERE parent='0' ORDER BY sort ASC";
$folders = $db->prepare($sql);
$folders->execute();
$folder = $folders->fetchAll();
if ($folder) {
echo "<table>";
echo "<thead>
<tr>
<td>Label</td>
<td>Sort</td>
<td>Id</td>
</tr>
</thead>";
foreach ($folder as $folderr) {
echo "<tr class='folder-item'>";
if($folder['link'] == 'folder'){
echo" <td><i class'fa fa-folder'><a href='#' onclick='get_data(".$folderr['id'].")'>".$folderr['label']."</a></td>";
}else{
echo" <td><i class='fa fa-file'></i><a href='#' onclick='get_data(".$folderr['id'].")'>".$folderr['label']."</a></td>";
}
echo" <td>".$folderr['sort']."</td>
<td>".$folderr['id']."</td>
</tr>";
}
echo "</table>";
} else {
echo 'No folder/files found.';
}
?>
</div>
</div>
</main>
</div>
here's the script
<script>
function get_data(id){
$.ajax({
type : 'GET',
url : 'file.php',
data : 'folder=' + id,
success : function(response){
$('.load-data').html(response);
}
});
}
$('.folder-item a').on('click', function() {
var $this = $(this),
$bc = $('<div class="item"></div>');
$this.parents('td').each(function(n, td) {
var $a = $(td).children('a').clone();
$bc.append(' > ', $a);
});
$('.breadcrumb').html( $bc.prepend('Document') );
return false;
});
</script>
here's the file.php
<?php
require_once 'config.php';
if(isset($_GET['folder'])){
$id = $_GET['folder'];
$sql = "SELECT * FROM tbl_menu WHERE parent='$id' ORDER BY sort ASC";
$folders = $db->prepare($sql);
$folders->execute();
$folder = $folders->fetchAll();
if ($folder) {
echo "<table>";
echo "<thead>
<tr>
<td>Label</td>
<td>Sort</td>
<td>Id</td>
</tr>
</thead>";
foreach ($folder as $folderr) {
echo "<tr>";
if($folder['link'] == 'folder'){
echo" <td><i class'fa fa-folder'><a href='#' onclick='get_data(".$folderr['id'].")'>".$folderr['label']."</a></td>";
}else{
echo" <td><i class='fa fa-file'></i><a href='#' onclick='get_data(".$folderr['id'].")'>".$folderr['label']."</a></td>";
}
echo" <td>".$folderr['sort']."</td>
<td>".$folderr['id']."</td>
</tr>";
}
echo "</table>";
} else {
echo 'No folder/files found.';
}
}
?>

Displaying Data from Database Using PDO, Table is empty

I'm trying to display MySQL database information into HTML. I've researched 20+ topics in this forum on the subject, trying to use their solutions, yet I am still having issues. The following code is being executed. I'm trying to read the courseNumber, section, instructor, startTime, endTime, days, and name from a database. I thought that the foreach would display all of my data from the query, but there is nothing being displayed, only my table headers and user input button at the bottom. I have made sure that the database is populated. I've attempted to use a while loops and different foreach loops from online solutions, but haven't had any luck. If it isn't obvious, I'm a programming student and am trying to get a grasp on the subject. All time and effort is greatly appreciated!
this is the website i'm uploading to http://einstein.etsu.edu/~latture/hw4/main.php
//this is the function I'm using to call my database. This part is working correctly(executed below)
static function readAll()
{
$pdo = Database::connect();
$sql = "Select * from course";
$data = $pdo->prepare($sql);
$data->execute();
$data->fetchAll();
Database::disconnect();
return $data;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<style>
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
<title></title>
</head>
<body>
<div class="row">
<div class="col">
<table class="table">
<thead>
<tr>
<th>Course Number</th>
<th>Section</th>
<th>Instructor</th>
<th>Start Time</th>
<th>End Time</th>
<th>Days</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php
include_once "courseController.php";
include_once "schedule.php";
include_once "student.php";
$courses = courseController::readAll();
foreach($courses as $courseDB) {
echo '<tr>' .
'<td>' . $courseDB['courseNumber'] . '</td>' .
'<td>' . $courseDB['section'] . '</td>' .
'<td>' . $courseDB['startTime'] . '</td>' .
'<td>' . $courseDB['endTime'] . '</td>' .
'<td>' . $courseDB['instructor'] . '</td>' .
'<td>' . $courseDB['days'] . '</td>' .
'<td>' . $courseDB['name'] . '</td>' .
'</tr>';
}
?>
</tbody>
</table>
</div>
</div>
<div class="row">
<form = method ="post" action = "process.php">
<div class = "col">
<div class="form-group">
<select class="form-control" name="ActionType">
<option id="create" value="create">Create!</option>
<option id="update" value="update">Update..</option>
<option id="delete" value="delete">Delete :(</option>
</select>
</div>
</div>
<div class = "col">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
</body>
</html>
You have to return result received from $data->execute();. change your readAll() as below
static function readAll()
{
$records = array();
$pdo = Database::connect();
$sql = "Select * from course";
$data = $pdo->prepare($sql);
$data->execute();
$records = $data->fetchAll();
Database::disconnect();
return $records;
}
you should use this
$data= $pdo->query($sql);
$result = $query->rowCount();
if($result > 0){
$r = $result->fetchAll();
}else{
$r = 0;
}
return $r;

How do I print the page without the datatable

I'm trying to print the data from the sql for record purposes but I'm using datatable so when I try to click print, the record doesn't show everything. It only shows the current data from the page 1 of the datatable. How will I do it? Plus, when I tried printing it, the display also shows the include function of the php. Javascript solutions are allowed. Here is my code
<?php include ('sidebar.php'); ?>
<main id="playground">
<?php include ('header.html'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<section class="panel panel-info">
<header class="panel-heading">
<h4 class="panel-title">List of employees</h4>
</header>
<div class="panel-body">
<?php
include('configuration.php');
$sql = "SELECT firstname, lastname, status, idnumber FROM employees ORDER BY lastname ASC";
$result = $conn->query($sql);
?>
<table class="table table-striped datatable" id="datatables" >
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>ID Number</th>
</tr>
</thead>
<?php
if ($result->num_rows > 0) { // output data of each row?>
<tbody>
<button onclick="myFunction()">Print this page</button>
<?php while($row = $result->fetch_assoc()) {
if($row['status']=='p'){
?>
<?php { //this form will display the set of pending applications
echo'<tr>';
echo '<td>' . $row['lastname'] . '</td>';
echo '<td>' . $row['firstname'] . '</td>';
echo '<td>' . $row['idnumber'] . '</td>';
echo'</tr>';
}
?>
<?php } //if statement
} //while statement
?>
</tbody>
</table>
<?php
}else {
echo "0 results";
}
?>
</div>
</section>
<!-- end of STRIPED ROWS TABLE -->
</div> <!-- / col-md-12 -->
</div> <!-- / row -->
</div> <!-- / container-fluid -->
</main> <!-- /playground -->
<?php include ('notifications.html'); ?>
<div class="scroll-top">
<i class="ti-angle-up"></i>
</div>
</div> <!-- /animsition -->
<script>
function myFunction() {
window.print();
}
</script>
</body>
</html>
Please use
$('#datatables').DataTable( {
buttons: [
'print'
]
} );
Please check Document and Reference
Use Below 2 functions:
function CreateTableFromObject(tblObj) {
objHeader = JSON.parse(JSON.stringify(tblObj.buttons.exportData()))["header"];
objRows = JSON.parse(JSON.stringify(tblObj.buttons.exportData()))["body"];
//Check If Action Exists in Table and remove it
var index = objHeader.indexOf('Action');
if (index > -1) {
objHeader.splice(index, 1);
}
tblToPrint = "<table style='border: 1px solid black; border-collapse: collapse;'><thead><tr>";
$.each(objHeader, function (key, value) {
tblToPrint += "<th style='border: 1px solid black;'>" + value + "</th>";
});
tblToPrint += "</tr></thead><tbody>";
$.each(objRows, function (key, value) {
tblToPrint += "<tr>";
//If action exists then decrease target by 1
if (index > -1) {
target = value.length - 1;
}else {
target = value.length;
}
for (var i = 0; i < target; i++) {
tblToPrint += "<td style='border: 1px solid black;'>" + value[i] + "</td>";
}
tblToPrint += "</tr>";
});
tblToPrint += "</tbody></table>";
return tblToPrint;
}
function PrintWindowAddParts() {
var tblObj = $("#YourTable").DataTable();
var tblViewRMA = CreateTableFromObject(tblObj);
var printContents = "<div class='dataTables_wrapper form-inline dt-bootstrap'>" + tblViewRMA + "</div>";
var size = 'height=' + $(window).height() + 'px,width=' + $(window).width() + 'px';
var mywindow = window.open('', 'PRINT', size);
mywindow.document.write('<html><head><title>' + "My Title" + '</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<h4>' + "My Title" + '</h4>');
mywindow.document.write(printContents);
mywindow.document.write('</body></html>');
mywindow.document.close();
mywindow.focus();
mywindow.print();
mywindow.close();
return true;
}
Your Print function is Ready.

Fixing a pagination error

I am having a problem with pagination within the tabs. In the second tab (candidate), when I press pagination 2 to navigate to the second page of the candidate table, I am returned to the first page of the contact table. If I go to the candidate tab after that I am on the right page. Where have I gone wrong?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/start/jquery-ui.css"/>
<link type ="text/css" rel ="stylesheet" href = "testData.cs"/>
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
});
</script>
<head>
<title>Candidate DB</title>
</head>
<body>
<div id ="tabs1" class ="contactForm">
<ul>
<li>List of Contacts</li>
<li>List of Candidates</li>
<li>Advanced Search</li>
</ul>
<div id ="tab1" class="contact" >
<table border="1" id="contact_info">
<tr>
<th>Contact Name</th>
<th>County</th>
</tr>
<?php
$DB_NAME = "Candidate";
$DB_USER ="root";
$DB_PASSWORD ="";
$DB_HOST ="localhost";
$con=mysql_connect("$DB_HOST", "$DB_USER", "$DB_PASSWORD") or die("Could not connect to MySQL");
mysql_select_db("$DB_NAME") or die ("No Database");
echo "Connected to Candidate Database </br></hr>" ;
$per_page=5;
$pages_query= mysql_query("SELECT COUNT(contact_id) FROM contact");
$pages = ceil(mysql_result($pages_query,0)/$per_page);
$page=(isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start=($page-1) * $per_page;
$sql=mysql_query("SELECT first_name, last_name, county from contact ORDER BY last_name ASC LIMIT $start, $per_page" );
$Fname = 'first_name';
$Lname = 'last_name';
$county = 'county';
while ( $row = mysql_fetch_object($sql)) {
echo "<tr>";
echo "<td>" . $row ->first_name . " " . $row->last_name. "</td>";
echo "<td>" . $row->county . "</td>";
echo "</tr>";
}
// close the loop
if ($pages>=1 && $page<= $pages ) {
for ($x=1; $x<=$pages; $x++)
{
echo ($x ==$page)? '<strong><a style="color:green" href="? page='.$x.'">'.$x. '</a></strong>_':''.$x. '_';
}
}
?>
</table>
</div>
<div id ="tab2" class="candidate" >
<table border="1" id="candidate_info">
<tr>
<th>Candidate Name</th>
<th>County</th>
</tr>
<?php
$per_pageR=5;
$pages_queryR= mysql_query("SELECT COUNT(candidate_id) FROM p_candidate");
$pagesR = ceil(mysql_result($pages_queryR,0)/$per_pageR);
$pageR=(isset($_GET['pageR'])) ? (int)$_GET['pageR'] : 1;
$startR=($pageR-1) * $per_pageR;
$sql2=mysql_query("SELECT R_first_name, R_last_name, R_county from p_candidate ORDER BY R_last_name ASC LIMIT $startR, $per_pageR" );
$R_name = 'R_first_name';
$R_name = 'R_last_name';
$R_county = 'R_county';
while ( $rowR = mysql_fetch_object($sql2)) {
echo "<tr>";
echo "<td>" . $rowR ->R_first_name . " " . $rowR->R_last_name. "</td>";
echo "<td>" . $rowR->R_county . "</td>";
echo "</tr>";
}
// close the loop
if ($pagesR>=1 && $pageR<= $pagesR ) {
for ($y=1; $y<=$pagesR; $y++)
{
echo ($y ==$pageR)? '<strong><a style="color:green" href="? pageR='.$y.'">'.$y. '</a></strong>_':''.$y. '_';
}
}
?>
</table>
</div>
</div>
</body>
If I understand correctly, try using the active option - http://api.jqueryui.com/tabs/#option-active - when you do .tabs() to make the candidate tab the active tab.
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo "{ active: 1 }"; ?>);
});
</script>
or
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo '"option", "active", -1'; ?>);
});
</script>
edit
You could bind the .tabs() first, and then set the active option. This should hopefully fix your formatting issue.
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
<?php if(isset($_GET['pageR'])) { ?>
$('#tabs1').tabs("option", "active", -1)
<?php } ?>
});
</script>

Categories