How to ajaxify a PHP function that does SQL in the backend? - php

I have broken down my problem to provide a concise example with no overhead.
Yet enough to give you an idea.
I have a simple index.php
<?php
include 'myClass.php';
?>
<html>
<head></head>
<body>
<div> <?php myClass->printTable(); ?> </div>
</body>
</html>
The function returns an entire table filled with data that is being prepared in the backend.
<?php
function printTable()
{
// printing static table header
echo ' <table class="table" style="zoom: 0.75;">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th> // current date
<th scope="col">Order Number</th> // an int
<th scope="col">Current Value</th> // an int
</tr>
</thead>
<tbody>
';
$result = mysqli_query($this->link, "SELECT * FROM `someData`");
while ($row = mysqli_fetch_assoc($result))
{
$orderNumber = $row['orderNumber'];
$currentValue = $row['currentValue'];
$date = $this->getDate($orderNumber); // member function that returns a timestamp from the database
//printing actual table
echo ' <tr>
<td>'. $date .'</td>
<td>'. $orderNumber .'</td>
<td>'. $currentValue .'</td>
</tr>
';
}
echo ' </tbody>
</table>
';
}
?>
The data I'm querying from my database is constantly changing. I want a "live" view on the frontend. I know this is done by using Ajax. But I don't understand how to do it. I looked up different resources, although none of them were actually specific enough in this approach.

On a high level: You need a PHP file ("endpoint", e.g. 'localhost/data.php') returning only the HTML code from printTable. You then use JavaScript (e.g. jQuery - $.ajax, you can lookup how it works in detail) to fetch the contents of this page each n seconds and insert into your page.

I was looking for broad or unspecific way to get some data from the backend and display it within a div on my page.
The solution was to create a separate PHP (fetch.php) file that echoes only the data I need to display within my div
from my page which contains my div I'd do the following:
<div id="result"></div>
<script>
function load_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#result').html(data);
}
});
}
load_data()
</script>
Inside fetch.php I can do whatever I want, including querying my database and store the values in a variable which will be echoed at the end. This response (echo) from fetch.php will then be displayed inside my div.
Similarly, I could also specify a .txt inside the ajax function (url:"sometext.txt")
The contents of the .txt could also be displayed inside my div this way. My lack of understanding of how this works made it really difficult to understand.
Additionally, I have added a function to refresh the contents (or response) every second.
If I would echo time() from fetch.php it would automatically increment without page reload inside my div
setInterval(function(){
load_data()
}, 1000);

Related

document.getElementById() as PHP SQL Query parameter

I have a question, is it possible to use the value stored in document.getElementById().value, getElementsByName().value, getElementsByClassName().value as a parameter for SQL Query via PHP?
Example.
I have this line <input type="text" class="myinput" id="myinput" name="myinput" value="999-AAA-000">
Then I'll store the data in this element.
<script>
function myFunction() {
var foroutput = document.getElementsByClassName("myinput");
}
</script>
Is there a way for document.getElementsByClassName("myinput"), or var foroutput to be used as a parameter for SQL Query via PHP?
SCENARIO: The SQL Query is within the same page as the document.getElementsByClassName("myinput"), will this work without using <form>?
This is my code
<input type="text" class="decid" id="decid" name="decid">
// the data passed into this input box will be used as a parameter for SQL Query $id
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
<?php
$id=$_POST['id'];
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
";
}
?>
</tbody>
</table>
A sample would be extremely great. Thank you.
EDIT:
Why won't this work?
<input type="text" class="decid" id="decid" name="decid">
<script type="text/javascript">
var abc = document.getElementById("decid").value;
<?php $abc = "<script>document.write(abc)</script>"?>
</script>
<?php echo $abc;?>
It looks as if you think <?php $abc = "<script>document.write(abc)</script>"?> might store the result of running JavaScript in a PHP variable. This is impossible. PHP runs on the server and builds the HTML to send to the client's browser. The JavaScript does not get run until it is received by the browser.
Server-side:
- PHP and MySQL can be run
- JavaScript cannot be run
Client-side:
- JavaScript can be run
- PHP cannot
In your example
<input type="text" class="decid" id="decid" name="decid">
<script type="text/javascript">
var abc = document.getElementById("decid").value;
<?php $abc = "<script>document.write(abc)</script>"?>
</script>
<?php echo $abc;?>
Is actually the same as
<input type="text" class="decid" id="decid" name="decid">
<script type="text/javascript">
var abc = document.getElementById("decid").value;
</script>
<script>document.write(abc)</script>
Because you stored a string with script tags in it inside of the variable $abc, and then echoed that variable back out a couple of lines later.
There are a few ways of getting JavaScript to communicate with the server.
1)
The old fashioned way is just to refresh the page with a query parameter that tells PHP what myinput is.
window.location.href = 'http://example.com/mypage?myinput=' + abc
And then in PHP you can get the input and use it in your SQL Query like so.
$abc = $_GET['myinput'] ?? false;
if ($abc){
...
}
2)
A better way is to use Ajax. Ajax allows you to send a request to the server for some data without having to refresh the entire page. If you're using jQuery then you can do this with the jQuery.get or jQuery.load functions. You would then have PHP return you your results which you would add to the page. There are a lot of tutorials out there on how to do this.
3)
If you're not using jQuery, then there are 2 additional options for sending requests to the server. If you don't care about supporting IE 11, then you can use the new Fetch API. The other option is to use the axios library which is a little bit easier to use, but requires installing a third party library. They are both pretty similar in their use.

Hello i'm trying to do multiple sorting using php mysql where i'm searching and then sorting the data

i'm printing a table in php where data is coming from mysql now i'm creating functionalities like searching and sorting so when i click on sort it sorts the data and when i click on search i get searched data now the problem is i want to perform sorting on searched data like for example i sorted the data and then i searched for words starting with a i.e i got results like adam,azan,anand so i want to perform resorting on these searched data and get data as adam,anand,azan
my approach is:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here Get Sort Content is a function calling Store Procedure SortContent which is working at first sorting
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
and i'm talking in context of large amount of data i hope i have made myself clear and if possible how can i implement ajax using mysqli
You will need to trigger an event in JavaScript, which in turn will use your HTML search input, which is then sent to the server, where a query will be executed and the results returned (as HTML) to the JavaScript code, and finally placed back on the page. At least this is how I solve my ajax searches...
So the flow could be something like:
Input -> JavaScript event -> ajax -> result -> page
Here is some code that might get you started, though I haven't tested i myself:
HTML:
<input type="text" id="my_search_input">
<div id="my_search_result"></div>
JS (jQuery):
var $inputField = $( "#my_search_input" );
var $result = $( "#my_search_result" );
$inputField.on('keyup', function(){ //triggered when a pressed key is lifted
var searchTerm = $inputField.val();
$.ajax({
url:"/mySearch.php",
method:"post",
data:{searchTerm:searchTerm},
success:function(response){ //response contains the data from mySearch.php
var parsedResponse = JSON.parse(response);
var resultHtml = parsedResponse.html; //this is the array key of what the PHP script returns
$result.append(resultHtml);
}
});
});
PHP
$searchTerm = $_POST['searchTerm']; //$_POST['searchTerm'] is what we defined in data:{... in the ajax call
// here is where you need to retrieve data from your database
// the db result needs to be processed into HTML and assigned to a variable
$html = "<div>My result based on data</div>";
return json_encode(['html' => $html]);

Datatable: update table in realtime with animation

I am trying to implement functionality where it updates data in real time of my datatable with animation just like facebook ticker (last friends activities on the sidebar) but no solution found !
model file :Topic.php
public function getTopics()
{
return $this->db->select('SELECT * FROM topics');
}
index file:
<table id="example" class="table table-striped table-bordered" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>Sujet</th>
<th>Pièce jointe</th>
<th>Coordonnées</th>
</tr>
</thead>
<tbody>
<!--content table -->
<?php
if($data['topics']){
foreach($data['topics'] as $row){
echo '<tr>';
echo '<td>'.$row->id.'</td>';
echo '<td>'.$row->subject.'</td>';
echo '<td>'.$row->document.'</td>';
echo '<td>'.$row->x.','.$row->y.'</td>';
echo '</tr>';
}
}
?>
</tbody>
</table>
controller:
$data['topics'] = $this->_topic->getTopics();
$data['js'] = "<script>
$(document).ready(
function ()
{
$('#example').DataTable().ajax.reload();;
}
);
</script>";
View::renderTemplate('header');
View::render('account/topics', $data);
View::renderTemplate('footer', $data);
This is called real time functionality! There are a few days to do it!
Use ajax to update data and setInterval on the ajax function for maybe like 5s or 10s whatever you like.
The other way that I'd do is by using getting an API Pusher. Pusher is a real time functionality web app! It can be used to achieve real time functionality on your site!
You can use setInterval() to check for topics every x seconds, minutes etc:
setInterval(function(){
$.ajax({
type: 'GET',
url: 'path/to/query',
success:function(data){
if(data != ""){
$('#datatable-table').dataTable()._fnAjaxUpdate();//reloads table, syntax will differ based on datatables version
}
}
})
}, 5000);//every 5 seconds
This is only an example. You'll need to plan (for example, what happens when the response takes longer than 5 seconds?)

how to access the returned php variable using ajax, as a php variable in the view

i am in this situation,
//view
$.ajax({type: 'POST',
url: base_url+"home/display_info/"+patient_id,
async: false,
success: function(data){
//alert(data);// alert was working
}
});
//controller
function display_info($id)
{
$document= $this->document_model->getDocumentOfPatient($id);
print_r($document);
}
in this i am getting the data as an array from the controller, and i want to get the data to a php array variable to build a table(html) with that array,but stuck here, is there any way to set a table(html) with this returned data variable, can i access the variable <?php echo $document['document_id'];?> like this in the view.
Try this
First you create table in your view page. Table id name foo and use to create table row and append to the html table
Sample code is given below
<scrit type="text/javascript">
$.ajax({type: 'POST',
url: base_url+"home/display_info/"+patient_id,
async: false,
success: function(data){
var table = '<tr><td>' + data['patient_id'] + '</td><td>' + data['document_id'] + '</td><td>' + data['document_date'] + '</td><td>'+ data['insert_user_id']+ '</td></tr>';
$('#poo > tbody').append(table);
}
});
</script>
<table id="poo" style="margin:10px 0px 0px 0px;" width="100%" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<td><strong>Product id</strong></td>
<td><strong>Doc id</strong></td>
<td><strong>Date</strong></td>
<td><strong>userid</strong></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
PHP is a server-side language. If you want to use PHP data in your view, you need to convert it to a client-side language like Javascript.
For example, in your display_info controller, you could return some JSON, using PHP's json_encode to convert a PHP array made of useful data for your view. Output it with the application/json content-type header.
In this kind of situation I used to make table in controller itself and assign it to variable.
So you can get that table in View as AJAX Response. Then its very simple to assign response to
inner HTML of resource Id where its required to display.
Does the data correctly ?
var obj = jQuery.parseJSON(data);
use JSON in the form of.I hope the right understand

Why I am having problems with my output using html/jquery/php

Problem no 1 Why my table do not align?
Problem no 2 Why everytime I click my Warrior List at the nav the output goes like this
Here's my js
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
success: function(data) {
$('#listWarriors').append(data);
}
});
}
Here's my html
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</table>
</article>
And heres my php
foreach($result as $names){
$warriors['wname'] = $names['warrior_name'];
$warriors['wtype'] = $names['warrior_type'];
echo '<tr>
<td>'.$warriors['wname'].'</td>
<td>'.$warriors['wtype'].'</td>
</tr>';
}
the result is appended under the </table>
try change your ajax success to :
$('#listWarriors table').append(data);
for number2, im affraid it's truncated by the container (#listWarriors)..
check your css of that id if the width is fixed or not...make it wider as you please
The way you have your jQuery, you are appending the content to the '' tag, and not to the table.
This is what happens when each item is appended, with the way its setup (I added a thead tag by the way. Will come in handy once you start styling your table)
This is the output when things are appended, and why its rendering wrong.
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<thead>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</thead>
</table>
<tr>
<td>the wname</td>
<td>the wtype</td>
</tr>
</article>
With that said modify your jquery to
$('#listWarriors table').append(data);
By the way,
How many items are you wanting to append. If you will make multiple ajax calls and append things one at a time, I would recommend getting the data through JSON. Let me know, if I can help
AS DISCUSSED IN COMMENTS SINCE YOU WANT TO GET MULTIPLE ITEMS JSON IS THE WAY TO GO. You can pass data using JSON this way
**The php (Im sure you already have the query already done but here it is just in case) **
// Make a MySQL Connection
$query = "SELECT * FROM example";//Your query to get warriors from db
$result = mysql_query($query) or die(mysql_error());
$myWarriorsArray = array();//Where you will store your warriors
while($row = mysql_fetch_array($result)){
$myWarriorsArray[] = $row;
//This stores all keys for each iteration
/*//This is teh same as the following commented code
$myWarriorArray['warrior_name'] = row['warrior_name'];
$myWarriorArray['warrior_type'] = row['warrior_type'];
*/
}
echo json_encode($myWarriorsArray);//This will return a json object to your ajax call
The Javascript
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
dataType : 'json',
success: function(data) {
var toAppend = '';
alert(data);
//console.log(data);//Uncomment this to see the returned json data in browser console
for(var i=0;i<data.length;i++){//Loop through each warrior
var warrior = data[i];
toAppend += '<tr>';
toAppend += '<td>'+data[i]['warrior_name']+'</td>';
toAppend += '<td>'+data[i]['warrior_type']+'</td>';
toAppend += '</tr>';
}
$('#listWarriors table').append(toAppend);
}
});
}

Categories