Issue getting jQuery Data-tables to work - javascript

I was tryin to create something quick to use data tables but I am having issues with jQuery I keep getting jQuery undefined and $ undefined. I thought I had put jQuery in the correct order. I am little stumped on what to do. I know it something simple so I will continue to figure it out.
Index.php
<div class="container">
<h1>Example List</h1>
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Equipment</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<?php
<?php
$db = new PDO('mysql:host=localhost;dbname=database;charset=utf8mb4', 'user', 'password');
$stmt = $db->query('SELECT * FROM table');
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{ ?>
<tr>
<td><?php echo $row['date'];?></td>
<td><?php echo $row['equipment'];?></td>
<td><?php echo $row['qty'];?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php //script section ?>
<link rel="stylesheet" href="bootstrap.min.css">
<scriptsrc="jquery.js"></script>
<script src="jquery.dataTables.min.js"></script>
<script>
$('.table').DataTable();
</script>

Going for the low hanging apple here, but is <script src="jquery.js"></script> present as-is in your index? Seems to be a typing error.

Related

Database not showing up in Webpage

I'm trying to get a database to show up in a table according to an assignment(this is a college course). I have followed the instructions to the letter but I can't get the table to show up on the webpage. From what I can tell the database seems to be working properly and the Webpage shows up as intended but the table is empty. Right no the assignment is just setting up the early part of the program but the instructions say this should be working.
<?php
require_once 'login.php';
$pdo = new PDO($attr, $user, $pass, $opts);
// Get Pages via Get Request //
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
// Set Records to show per page //
$results_per_page = 5;
$stmt = $pdo->prepare('SELECT * FROM contacts ORDER BY c_id LIMIT :current_page, :results_per_page');
$stmt->bindvalue(':current_page', ($page-1)*$results_per_page, PDO::PARAM_INT);
$stmt->bindvalue(':results_per_page', $results_per_page, PDO::PARAM_INT);
$stmt->execute();
// Fetch the Records //
$contacts = $stmt->fetchALL(PDO::FETCH_ASSOC);
// Get the total contacts //
$num_contacts = $pdo->query('SELECT COUNT(*) FROM contacts')->fetchColumn();
?>
<!doctype html>
<html lang="en">
<head>
<title>Contact Directory</title>
<link href="./styles.css" rel="stylesheet" type="text/css">
<style>
<?php include "./styles.css" ?>
</style>
</head>
<body>
<header><img src="Diamonds.png" alt="Diamonds">My Contact List</header>
<nav>
<div class="navtable">
<ul id="navbar">
<li>Placeholder</li>
<li>Placeholder</li>
</ul>
</div>
</nav>
<content>
<div class="content">
<h2>Read Contacts
Create Contact
<table>
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Title</td>
<td>Created</td>
<td></td>
</tr>
</thead>
<tbody>
<?php foreach($contacts as $contact): ?>
<tr>
<td><?php $contact['c_id']?></td>
<td><?php $contact['c_name']?></td>
<td><?php $contact['email']?></td>
<td><?php $contact['c_phone']?></td>
<td><?php $contact['title_id']?></td>
<td><?php $contact['created']?></td>
<td class="actions">
Edit
delete
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="page_advance">
<?php if ($page >1): ?>
Next->
<?php endif; ?>
<?php if ($page*$results_per_page < $num_contacts): ?>
<-Prev
<?php endif; ?>
</div>
</div>
</content>
<footer>
<div class="copyright">
<p>© Copyright 2022 by Ian Sikes-Cook, this site is for a class project</p>
</div>
</footer>
</body>
</html>

How to fetch results from MySQL database using AJAX on button click

I am new to PHP and ajax so please be easy on me. I am trying to fetch MySQL results using AJAX. I have manged to get to this point from the research I found across the internet. I am doing this inside WordPress if this might help. I am getting this error -
Uncaught Error: Call to a member function get_results() on null in script.php:13 Stack trace: #0 {main} thrown in script.php on line 13
test.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button type="button">Click</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<p></p>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("button").click(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
jQuery("p").html(data);
}
});
});
});
</script>
</body>
</html>
script.php
<?php
echo' <table border="1">
<th colspan="5" style="text-align:center;"> <h2 class="tomorrow">GRADES</h2> </th>
<tr>
<th>Day</th>
<th>Comp</th>
<th>Exam Type</th>
<th>Grade</th>
<th>Previous Score</th>
</tr>'?>
<?php
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM wp_mytab
WHERE date=DATE(NOW())
UNION ALL
SELECT * FROM wp_mytabb
WHERE date=DATE(NOW())
ORDER BY date, comp ASC;" );
foreach ( $result as $print ) {
?>
<tr>
<td><?php echo $print->day;?></td>
<td><?php echo $print->comp;?></td>
<td><?php echo $print->examtype;?></td>
<td><?php echo $print->grade;?></td>
<td><?php echo $print->previouscore;?></td>
</tr>
<?php }
?>
</table>
?>
What could be wrong here?
You can't use $wpdb outside of wordpress code structure in a stand alone PHP file.
To do that you should include some wordpress libraries
Add this at beginning of your php code.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-includes/wp-db.php';
Make sure your $path be right

JQuery Datatable plugin doesn't work correctly in CodeIgniter 3.x

This'll be my first time posting here.
Please forgive my little knowledge on programming. I'm fairly new to PHP with just 3 weeks of practice. I've just been working on a simple CodeIgniter 3.x project using Netbeans, for around the same time I'm practicing PHP. I'd like to output a simple datatable using the JQuery Datatable plugin from here. I think I've followed the simple 'Your first datatable' example posted there correctly. Though I don't understand why my code won't work.
Here's my index.php, which is the view:
<html>
<head>
<title>
Employee Database
</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/datatable-bootstrap.min.css" media="screen">
<script type="text/javascript" src="<?php echo base_url(); ?>js/jquery-3.2.1.js"></script>
<script type="text/javascript" src="<?php echo base_url(); ?>js/datatable.jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
<script src="<?php echo base_url(); ?>js/index.js"></script>
</head>
<body>
<header>
<center>
<h1>
Employee DB
</h1>
</center>
</header>
<center>
<table class="table table-bordered">
<thead>
<tr>
<th>
Employee Code
</th>
<th>
Employee Description
</th>
<th>
Employment Date
</th>
<th>
Dept. Code
</th>
<th>
Dept. Description
</th>
</tr>
</thead>
<?php foreach ($results as $results_item): ?>
<tbody>
<tr>
<td>
<?php echo $results_item['empcode']; ?>
</td>
<td>
<?php echo $results_item['empdesc']; ?>
</td>
<td>
<?php echo $results_item['empdate']; ?>
</td>
<td>
<?php echo $results_item['deptcode']; ?>
</td>
<td>
<?php echo $results_item['deptdesc']; ?>
</td>
</tr>
</tbody>
<?php endforeach; ?>
</table>
<div id="paging-first-datatable"></div>
<!--<?php //var_dump($results);?>-->
</center>
</body>
</html>
here's my index.js:
$('#first-datatable-output table').datatable({
pageSize: 10,
sort: [true, true, true, true, true],
filters: [true, true, true, true, true],
filterText: 'What do you wish to find?'
});
It doesn't seem to work. The only output I get is just a full table with nothing paginated. I console.log on my index.js javascript, to check whether I've linked them correctly, with a simple hello world and the message does output on the console as expected, the style.css seems to work too.
Any solution, response, and insight is deeply appreciated!
Thank you!!!
Okay so from the replies I got I finally managed to get it working!!
My only problem now is fixing the buttons for the pagination
They look something like this: Pagination
Any idea how to spruce it up?
You have the table body tags IN your foreach loop, which will output the tags for each result you have. You need to place them outside of your foreach.
Change this:
<?php foreach ($results as $results_item): ?>
<tbody>
<tr>
<td>
<?php echo $results_item['empcode']; ?>
</td>
<td>
<?php echo $results_item['empdesc']; ?>
</td>
<td>
<?php echo $results_item['empdate']; ?>
</td>
<td>
<?php echo $results_item['deptcode']; ?>
</td>
<td>
<?php echo $results_item['deptdesc']; ?>
</td>
</tr>
</tbody>
<?php endforeach; ?>
into this:
<tbody>
<?php foreach ($results as $results_item): ?>
<tr>
<td>
<?php echo $results_item['empcode']; ?>
</td>
<td>
<?php echo $results_item['empdesc']; ?>
</td>
<td>
<?php echo $results_item['empdate']; ?>
</td>
<td>
<?php echo $results_item['deptcode']; ?>
</td>
<td>
<?php echo $results_item['deptdesc']; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
The documentation states the tag is really important. Try this and let me know!
When reading the documentation you could also use JS directly. Maybe try that?
Try this for your index.js:
var datatable = new DataTable(document.querySelector('#first-datatable-output table'), {
pageSize: 10,
sort: [true, true, true, true, true],
filters: [true, true, true, true, true],
filterText: 'What do you wish to find?'
});
I inspected the source code of the Documentation. They put the table into a div with the id first-datatable-output... They do not document that anywhere.
You could try to put this <div id="first-datatable-output"> BEFORE <table class="table table-bordered"> and a </div> AFTER <div id="paging-first-datatable"></div>
For the pagination, try adding class="pagination-datatables text-center" to the <div id="paging-first-datatable"> like <div id="paging-first-datatable" class="pagination-datatables text-center">.
Holy... their documentation is baaaaaaaaad!

HTML, JQuery seporation of loading divs

I currently have a page that loads slow and would like to make the user experience more enjoyable. I would like to load each div so when a div is read() fade in using jQuery. Currently my code works but it loads everything at the same time and fades in. I would like it to load in order of div placement. Below is an example code of loading 2 divs with large tables in them. I would like each table to show up as soon as it's ready. The first one should be ready before the second one and it should render first. I have tried to separate the js so that each has their own ready() but that didn't work.
Also: I am more looking for a consent on how to do this rather than the specific code. What if I have a lot of divs with a lot of different tables. Not every div will have a table in it. some might have pictures or just text. There should be a way to load each div whenever it's ready to be displayed.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="style/jquery-ui.css" rel="stylesheet" type="text/css"/>
<link href="style/main.css" rel="stylesheet" type="text/css" />
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<title>Animated jQuery Fade | Script tutorial</title>
</head>
<script>
$(document).ready(function(){
$('.myTable').DataTable();
});
$(document).ready(function(){$(".content").hide().fadeIn(1000);});
</script>
<body>
<div id="header">
<h1>Welcome to test page</h1>
</div>
<div class="content" style="display: none;">
<table class="myTable">
<thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
</thead>
<tbody>
<?php for($i =0; $i <10000; $i++){ ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="content" style="display: none;">
<table class="myTable">
<thead>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
</thead>
<tbody>
<?php for($i =0; $i <20000; $i++){ ?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
<td><?php echo $i; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</body>
</html>
I think what you need here is to provide you DataTables with an AJAX source, which will retrieve your data. Then set a callback that will fire when the data has been loaded to fadeIn your tables.
It might look something like this:
$(document).ready(function() {
$('#myTable1').dataTable( {
"ajax"{
"url": 'path/to/datasource.php',
"success" : function(){
$('#myTable1').parent().fadeIn(1000);
}
}
} );
} );
This is untested code and the syntax may be wrong, but it should give you an idea of how this is done. Also, the returned data from your php datasource must return json in the correct format DataTables is expecting (this is very important, and is often where people make mistakes).
Please see the DataTables ajax docs here.
the problem is not about what type of data it need to display, but rather you should limit amount of data display each time, and separate the server side, from client side, so it will reduce load on browser, the code below is untested, prob lot of syntax error #_#
PHP
<?php
// you can manual hard code the data, or use database, it really didn't matter what the data are it can be path of image, text, etc...
var $textData = array(); // eg ('text1','text2')
var $imgData = array(); // eg ('path/img.jpg', 'path/img.jpg')
var $divData = array(); // eg ('<div class="parent"><div class="child"></div></div>')
// see what data set you want to get
if($_POST['type']==='text') {
// now encode the data into json for ajax
echo json_encode($textData);
} else if($_POST['type']==='img') {
echo json_encode($imgData);
}
?>
JQUERY AJAX
<script>
if(some condition are made) {
$.ajax({
url: "text.php",
type: "POST",
data: {
type: 'text' // it can be anything
},
dataType: "JSON",
success: function (dataSet) {
// jquery to append dataSet, use if() to append to different place depend on type
// this set you can hide as default with css
// after data loaded fade in with jquery.
}
});
}
</script>

jQuery's localtime plugin failed while loading content via ajax

I am using PHP & MySQL along with AJAX & jQuery to show contents from my database table.
PHP: serverside language as usual.
jQuery: to convert UTC time to local time based on user location. Thanks to jQuery localtime plugin :)
AJAX: to show contents of page2 into page1 on selecting a value from a drop down menu
Total no of pages: 2
Page1.php
I have an HTML table to which I show contents of all users. One of the values fetched from database is a UTC datetime variable.
To convert it into user's local time, I simply used a jQuery plugin. All that I had to do was add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
the above given files & then add a span <span class="localtime"> </span> in my table & echo the datetime variable into it. Viola! UTC time is now converted into user's local time.
In that same page, I have a dropdown menu showing list of all users from my database table. ANd on the onchange property of the drop down menu, I have called an AJAX function. This function will pass the username to page2.php & database opertaions are done in page2.php & results corresponding to that user is calculated & shown into an HTML table similar like to the HTML table I have in page1.php.
But in this table, UTC remains as such even though I tried adding the jQuery files in that page also. Why the jQuery localtime plugin didn't convert UTC time in page2 to localtime when it did the same in page1???
Here are two screen shots.
Page 1 before AJAX content loaded
Page1 after AJAX content loaded
Page1:
<html>
<head>
<title>Converting UTC time to Local time</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script>
function value_pass_func(uname)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//callback fn
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showtable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","page2.php?variable="+uname,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$connection = mysqli_connect('localhost','root','','dummydb') or die(mysqli_error($connection));
$query="SELECT distinct(user) FROM pagination ORDER BY id ASC";
$res = mysqli_query($connection,$query);
$count = mysqli_num_rows($res);
?>
</br>
</br>
</br>
<select id="ddl" name="ddl list" onchange="value_pass_func(this.value);">
<option selected value="">select any</option>
<?php
if($count>0)
{
while($row=mysqli_fetch_array($res))
{
$now=$row['user'];
?>
<option value="<?php echo $now; ?>"><?php echo $now; ?></option>
<?php
}
}
?>
</select>
</br>
</br>
<?php
$query1="SELECT * FROM pagination ORDER BY id ASC";
$res1 = mysqli_query($connection,$query1);
$count1 = mysqli_num_rows($res1);
if($count1>0)
{
?>
<div id="showtable">
<table class="table table-bordered table-responsive table-striped" border="1">
<thead>
<tr >
<th>id</th>
<th>post</th>
<th>user</th>
<th>now</th>
</tr>
</thead>
<tbody>
<?php
while($row1=mysqli_fetch_array($res1))
{
$idd=$row1['id'];
$post=$row1['post'];
$username=$row1['user'];
$datetime=$row1['now'];
?>
<tr>
<td><?php echo $idd; ?></td>
<td><?php echo $post; ?></td>
<td><?php echo $username; ?></td>
<td><span class="localtime"> <?php echo $datetime; ?></span></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php } ?>
</body>
</html>
Page2:
<?php
$un=$_GET["variable"];
$connection = mysqli_connect('localhost','root','','dummydb') or die(mysqli_error($connection));
$query="SELECT * FROM pagination where user='".$un."' ORDER BY id ASC";
$res = mysqli_query($connection,$query);
$count = mysqli_num_rows($res);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
<table class="table table-bordered table-responsive table-striped" border="1">
<thead>
<tr >
<th>id</th>
<th>post</th>
<th>user</th>
<th>now</th>
</tr>
</thead>
<tbody>
<?php
while($row=mysqli_fetch_array($res))
{
$idd=$row['id'];
$post=$row['post'];
$username=$row['user'];
$datetime=$row['now'];
?>
<tr>
<td><?php echo $idd; ?></td>
<td><?php echo $post; ?></td>
<td><?php echo $username; ?></td>
<td><span class="localtime"> <?php echo $datetime; ?></span></td>
</tr>
<?php
}
?>
</tbody>
</table>
You're loading jquery.. so I advise you to use it
The most simple answer to your question is to run this after your innerHTML replacement:
$.localtime.format(".localtime");
This will evaluate all of the elements again.
I suggest you do the following:
Use jquery's AJAX (link) to GET your table data.
Deliver your table data using JSON (link).
Personally I prefer to use Moment.js (link) to format my dates.
A basic jquery example..
Scripts on page1:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script>
$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");
function value_pass_func(uname)
{
$.ajax({
type: "GET",
url: "page2.php",
data: { variable: uname },
dataType: html
}).done(function(data) {
$("#showtable").innerHTML = data;
$.localtime.format(".localtime");
});
}
</script>
And drop those script tags in page2.
I haven't tested that localtime script but it probably does it's thing when fired

Categories