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

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

Related

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.

How to hide the result table on search bar?

I am not really good in coding, I need a help with my code. I have a code to search in a database. Now it's showing all the data on the database, when somebody search, it will filter out and show me result on the same table.I only want to show the result, when somebody search on the search bar, it should show me the filtered data. otherwise, my table should be hidden.
Can anybody please tell me how to do that. Thank you so much for your time.
<?php
if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `ADDRESS` WHERE CONCAT(`ID`, `STATE`) LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);
}
else {
$query = "SELECT * FROM `ADDRESS`";
$search_result = filterTable($query);
}
// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost:3306", "root", "dbadmin", "simplymac");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>SimplyMac PO Tracking Tool</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<style>
</style>
</head>
<body>
<div class="images-wrapper">
<img class="Large" src="/dbadmin/Images/simplymac_logo.png" width="320" height="140" />
</div>
<form action="index.php" method="post">
<div class="wrap">
<center><h3>PO TRACKING TOOL</h3></center>
<center><table>
<tr>
<td><input type="text" name="valueToSearch" placeholder="Enter Purchase Order (PO#) Number" size="100" class="searchbar"></td>
<td><input type="submit" name="search" value="SEARCH" class="Button"></td>
</tr>
</table></center>
</div>
<table class="resultdata">
<tr>
<th>ID</th>
<th>ADDRESS_LINE_1</th>
<th>ADDRESS_LINE_2</th>
<th>CITY</th>
<th>STATE</th>
<th>ZIP</th>
</tr>
<?php while($row = mysqli_fetch_array($search_result)):?>
<tr>
<td><?php echo $row['ID'];?></td>
<td><?php echo $row['ADDRESS_LINE_1'];?></td>
<td><?php echo $row['ADDRESS_LINE_2'];?></td>
<td><?php echo $row['CITY'];?></td>
<td><?php echo $row['STATE'];?></td>
<td><?php echo $row['ZIP'];?></td>
</tr>
<?php endwhile;?>
</table>
</form>
</body>
</html>
You can use ajax for your problem.
When customer type in text box at that time call one java script function, in this function get text box value and call ajax for result table.
function getResult(search)
{
var file_path = '';//your php file path
$.ajax({
type: "POST",
url: file_path,
data: search,
cache: false,
success: function(result){
//print result in one div
}
});
}
<input type="submit" name="search" value="SEARCH" class="Button" onClick="getResult(this.value);">

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

PHP Ajax MySQL Table Row Delete

I wrote the code to delete MySQL table rows. But when I click on delete icon, nothing happens. Could someone please tell me what's left in my code?
<?php
include_once 'include/DatabaseConnector.php';
$query1="SELECT * FROM MyTable;";
$result1=DatabaseConnector::ExecuteQueryArray($query1);
?>
<script type="text/javascript">
function deleteRow(tableName,colName,id){
$.ajax({
type: "POST",
url: "delete.php",
data: "tableName=tableName&colName=colName&id=id",
success: function(msg){
alert( "Row has been updated: " + msg );
}
});
}
</script>
<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
<th scope="col">Opr</th>
<th scope="col">Flt Num</th>
<th scope="col">From</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($result1 as $row):?>
<tr>
<td><?php echo $row['airlineName'];?></td>
<td><?php echo $row['flightNum'];?></td> <td><?php echo $row['from'];?></td>
<td>
<div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>
<img src='images/delete.png' alt='Delete' />
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
delete.php
<?php
/* Database connection */
include_once 'include/DatabaseConnector.php';
if(isset($_POST['tableName']) && isset($_POST['colName']) && isset($_POST['id'])){
$tableName = $_POST['tableName'];
$colName = $_POST['colName'];
$id = $_POST['id'];
$sql = 'DELETE FROM '.$tableName.' WHERE '.$colName.' ="'.$id.'"';
mysql_query($sql);
} else {
echo '0';
}
?>
have you checked your PHP log to see if there is an error?
what is Ajax.Request ? if you are using the prototype library, where is it included in your HTML code?
finally, are you sure your PHP code is called? (check using for instance the Web Developper Tools in Chrome browser, "Requests" tab)
You have an error on this line
<div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>
this will print
<div title='Delete' onclick='deleteRow(flightscheduleflightNumid)'>
You have to change it to
<div title='Delete' onclick='deleteRow("flightschedule","flightNum",<?php $row['flightNum']; ?>)'>
to work.
Best wishes
Update: For the above code to work also add
<script src="js/jquery.js" type="text/javascript" ></script>
or load it from the internet
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
to include Jquery at the header of html. I have tested its ok now.
you send not your data to the delete.php file, because in the attribute dated you seize them badly. Here is this code I have just tested him(it) and that seems to work.
data: "tableName="+tableName+"&colName="+colName+"&id="+id+"",
function deleteRow(tableName,colName,id){
$.ajax({
type: "POST",
url: "delete.php",
data: "tableName="+tableName+"&colName="+colName+"&id="+id+"",
success: function(msg){
alert( "Row has been updated: " + msg );
}
});
}

Categories