jQuery's localtime plugin failed while loading content via ajax - javascript

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

Related

Search and Pagination Functions not working in DataTable when using Dynamic Data

I made a table and I have been using Datatable CDN to have some functions such as search and the ability to select table pages. After following the steps on DataTables my code load my table with the search bar and pages, however all the functions are not working. Can someone tell me where I did a mistake please:
Using static data makes the dataTable work as it is intended with the search option and pagination working and showing the results that are in the table. However when using dynamic data with MySQL database the search and pagination functions stops working. Below is my code with fetch the data from table employees from my DB:
<?php
global $db;
$sql = "SELECT id, name, role, competency FROM employees";
$result = mysqli_query($db, $sql);
?>
This query is found just before my table in my html code, all the data are displayed correctly and styling of dataTable are displayed also, however the functions for search and pagination are not working. The search returns No Match result however the record is present in the table. Can someone please tell me the error please.
<table id="Data_Table" width="100%">
<thead>
<tr>
<td>ID</td>
<td>Employee Name</td>
<td>Job Role</td>
<td>Competency Level</td>
<td>Action</td>
</tr>
</thead>
<?php
if (mysqli_num_rows($result) > 0) {
foreach($result as $row) {
?>
<tbody>
<tr>
<form method="post">
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['role']; ?></td>
<td><?php echo $row['competency']; ?></td>
<td>
<button type="button" class="view_emp" title="View Record">
<span class="la la-eye"></span> View
</button>
<button type="button" class="edit_emp" title="Update Record">
<span class="la la-edit"></span>Update
</button>
<input type="checkbox" name="keyToDelete" value="<?php echo $row['id']; ?>" required>
<button type="submit" name="delete_employee" class="delete_employee" title="Delete Record"><span class="la la-trash"></span>Delete
</button>
</td>
</form>
</tr>
</tbody>
<?php
}
}
else {
echo "No Employee Record could be found";
}
$db-> close();
?>
</table>
In my code I have also included the script that would use DataTables as follows:
<script src="https://code.jquery.com/jquery-3.6.0.slim.js" integrity="sha256-HwWONEZrpuoh951cQD1ov2HUK5zA5DwJ1DNUXaM6FsY=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap5.min.js"></script>
and the style link for the datatable
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap5.min.css">
All the style are working as intended but the function such as search and pagination are not working can someone tell me what i made wrong here
I defined the DataTables in my script as follows:
<script>
$(document).ready(function(){
$('#Data_Table').DataTable();
});
</script>
There are no error in the console log of the browser the function search and pagination simply wont work, search option will search and return results as No match with records when there is a record and $results are the data fetched from my database employees eg: id: 1 ,name: Bob ,role: Web Designer ,Competency: Beginner.
In order to use DataTables, you need to inizialize one
$(document).ready( function () {
$('#Data_Table').DataTable();
});
This needs to be wrapped in a script tag
I don't see it anywhere in your code
Plus, you missed a td closing tag in Line 18
Here's a working example: jsfiddle.net
Source: datatables.net

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

Issue getting jQuery Data-tables to work

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.

PHP - pass hidden value into the jquery

<html>
<head>
<link rel="stylesheet" href="js/jquery-ui-themes-1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
</script>
</head>
<body>
<?php
//db connection
$query = "SELECT *
FROM department
ORDER BY dept_ID ASC";
$result = mysqli_query($dbc, $query);
$total_department = mysqli_num_rows($result);
if($total_department > 0)
{
?>
<table width="600" border="1" cellpadding="0" cellspacing="0" style="border-collapse:collapse">
<tr>
<td width="80" align="center">ID</td>
<td width="300" align="center">Department</td>
<td width="220" align="center">Action</td>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button class="buttonsPromptConfirmDeleteDepartment">Delete</button>
<input type="hidden" id="departmentID" value="<?php echo $row['dept_ID']; ?>" />
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
department table
dept_ID dept_name
1 Account
2 Finance
3 Marketing
Assume that my department table only have 3 records.
My requirement is the following:
- Click 1st delete button, show department ID = 1
- Click 2nd delete button, show department ID = 2
- Click 3rd delete button, show department ID = 3
However from my code, I can't meet my requirement. The department ID output that I get is 1 no matter what button I clicked.
Can someone help me?
No need to use a hidden input, you could just use the button tag instead:
<?php while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button type="submit" name="departmentID" class="buttonsPromptConfirmDeleteDepartment" value="<?php echo $row['dept_ID']; ?>">Delete</button>
</td>
</tr>
<?php } ?>
Of course, in the PHP script that does the form processing, access the POST index like you normally would:
$id = $_POST['departmentID'];
// some processes next to it
Note: Don't forget the <form> tag.
Additional Note: Don't forget to use prepared statements:
$sql = 'DELETE FROM department WHERE dept_ID = ?';
$stmt = $dbc->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
// some idea, use error checking when necessary
// $dbc->error
Change
id="departmentID"
to
class="departmentID" and
Change
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
to
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $(this).next('input.departmentID').val();
alert(departmentID);
});
});
first of all dept_id in while loop and you are using same id for all dept..
another thing you can get dept_id upon button click using jquery.. like this
$('.buttonsPromptConfirmDeleteDepartment').click(function(){
dept_id = $(this).next('input').val();
})

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>

Categories