I'm trying to do this example https://datatables.net/blog/2017-03-31 everything works except the ajax request, the problem is that I'm trying to return data from a database and a barely know how to do it with ajax (newbie) this is how my code and ajax request look:
var id = 0;
$('#tablanormal tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var tdi = tr.find("i.fa");
var row = table.row(tr);
id = 0;
id = parseInt(table.row(this).data().id_sol);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
tdi.first().removeClass('fa-minus-square');
tdi.first().addClass('fa-plus-square');
} else {
// Open this row
row.child(format(row.data())).show();
tr.addClass('shown');
tdi.first().removeClass('fa-plus-square');
tdi.first().addClass('fa-minus-square');
}
});
table.on("user-select", function (e, dt, type, cell, originalEvent) {
if ($(cell.node()).hasClass("details-control")) {
e.preventDefault();
}
});
});
function format(rowData) {
var div = $('<div/>')
.addClass('loading')
.text('Loading...');
$.ajax({
method: 'POST',
url: 'datatables_ajax/items.php',
data: {idsol: id},
dataType: 'json',
success: function (json) {
div
.html(json.html)
.removeClass('loading');
},
error: function (er) {
console.error(error)
}
});
return div;
}
item.php file
<?php
include_once '../datatables_ajax/conexion.php';
$objeto = new Conexion();
$conexion = $objeto->Conectar();
$idsol = $_POST['idsol'];
$consulta = "CALL Items('".$idsol."')";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
//print json_encode($data, JSON_UNESCAPED_UNICODE);
echo '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;"><tbody>';
foreach(['ID','item','number'] as $attribute) {
echo '<tr><th>'.$attribute.'</th>';
foreach($data as $row) {
echo '<td>'.$row[$attribute].'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
$conexion=null;
?>
items.php returns id_sol, item_name, item_number I wanted to return it first as text(it works if you only open the file) but the table just stay in "Loading..." when trying to show it, also it would be helpful if someone help me to return that data as a table.
First
you should remove the loading text when the ajax call is complete that's inside the complete: function(){} not inside the success: function(){}.
Second
you can return the data as a table from PHP like this:
if ($resultado->rowCount()){ //meaning if the request returned some data
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
$d = [];
$i = ;
foreach($data as $val){
$d[i]['fieldName'] = $val['columnName'];
}
echo json_encode($data);
}else{ //no data returned
//error handling here
}
Third
if you want to return the data as an HTML table then do this:
if ($resultado->rowCount()){ //meaning if the request returned some data
$data=$resultado->fetchAll(PDO::FETCH_ASSOC);
$output = "
<table>
<thead>
<tr>
<th>first header </th>
<th>second header </th>
</tr>
</thead>
<body>
";
$d = [];
$i = ;
foreach($data as $val){
$output .="
<tr>
<td>first header data=".$val[columnName]."</td>
<td>second header data=".$val[columnName]."</td>
</tr>";
$d[i]['fieldName'] = $val['columnName'];
}
$output .=" </tbody>
</table>";
echo json_encode($output);
}else{ //no data returned
//error handling here
}
Related
I am creating a list of links in main.php using "donemler" table in mySQL database and would like to create a page that shows data from "sikkeler" table (which has a foreing key donemID that is used as a relationship between the two tables) as the user clicks it. (data.php is a part of the index.php which is a infinite scroll page)
Here I tried to call $row["donemID"] with GET method using
$k=$_GET['donemID'] in index.php but did not work.
I have also tried to use SESSIONS method where I add "$_SESSION['donemID']=$row$row["donemID"] to main.php
and called it back in index.php as
$k=$_SESSION['donemID']
but it also did not work.
I would like to learn how to create pages and show relevant data in php.
Thanks in advance!
main.php
<?php
require_once "config.php";
$sql = $conn->query("SELECT * FROM donemler ORDER BY donemID");
if ($sql->num_rows > 0) {
// output data of each row
while($row = $sql->fetch_assoc()) {
echo "<tr><td><a href='index.php?devletID=".$row["devletID"]."&donemID=".$row["donemID"]."'>" .$row["donemler"]. "</a></td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php
<script type="text/javascript">
var start = 0;
var limit = 20;
var reachedMax = false;
var dnmID = $_GET("donemID");
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() )
getData();
});
$(document).ready(function () {
getData();
});
function getData() {
if (reachedMax)
return;
$.ajax({
url: 'data.php',
method: 'POST',
dataType: 'text',
data: {
getData: 1,
start: start,
limit: limit,
dnmID: dnmID,
},
success: function(response) {
if (response == "reachedMax")
reachedMax = true;
else {
start += limit;
$(".results").append(response);
}
}
});
}
</script>
data.php
<?php
if (isset($_POST['getData']) ) {
$conn = new mysqli('localhost', 'usrnm', 'pss', 'db');
$dnmID = $conn->real_escape_string($_POST['dnmID']);
$start = $conn->real_escape_string($_POST['start']);
$limit = $conn->real_escape_string($_POST['limit']);
$sql = $conn->query("SELECT * FROM sikkeler WHERE donemID='$dnmID' ORDER BY kayit_no DESC LIMIT $start, $limit");
if ($sql->num_rows > 0) {
$response = "";
while($data = $sql->fetch_array()) {
$response .= '
<tr>
<td>ICD#'.$data['kayit_no'].'</td>
<td>'.$data['donemi'].'</td>
<td><img src="coin_images/'.$data['resim'].'" border="2" width="200px" /></td>
<td>'.$data['darp'].'</td>
<td>'.$data['tarih'].'</td>
<td>'.$data['birim'].'</td>
<td>'.$data['agirlik'].'</td>
<td>'.$data['cap'].'</td>
<td>'.$data['tip'].'</td>
<td>'.$data['reference'].'</td>
</tr>
';
}
exit($response);
} else
exit('reachedMax');
}
?>
You are checking through two different request methods:
$_POST['getData']
$k=$_GET['donemID']
Since you are using the query strings, it is a GET method to check with.
There is no such variable i.e. getData on main.php
Now I can read the PictureName from database and show it on the browser. (Picture below: black block on the left)
And what I want to do is that, when do click on one of rows (ex: pic1), it will trigger function change().
But no matter what I try, function change() doesn't work. What should I do to my code? Thanks for the answers and suggestions. :)
read.php
<?php
require 'lib.php';
$object = new CRUD();
// table header
$data = '<table style="border-collapse:separate; border-spacing:0px 10px;">
<tr>
<th>No. </th>
<th>PictureName</th>
</tr>';
// table body
$picturetb = $object->Read();
if (count($picturetb) > 0) {
foreach ($picturetb as $key=>$picture) {
$data .= '<tr ng-click="change()">
<td>' . $key . '</td>
<td><a>' . $picture['Picture_Name'] . '</a></td>
</tr>';
}
}
$data .= '</table>';
echo $data;
?>
angular.js
var mainApp = angular.module("mainApp", []);
mainApp.controller('MyController', function ($scope) {
$scope.readRecords = function () {
$.get("ajax/read.php", {}, function (data, status) {
$(".addPicture").html(data);
});
}
$scope.change = function () {
console.log("do click");
}
}
Well you could use $compile but generally it is a very, very bad idea to inject markup this way. Why not return the key / picture as JSON:
$arr = [];
foreach ($picturetb as $key=>$picture) {
$arr[] = array('key' => $key, 'picture' => $picture['Picture_Name']);
}
echo json_encode($arr);
Retrieve it like this
$scope.readRecords = function () {
$.get("ajax/read.php", {}, function (data, status) {
$scope.data = data;
});
}
In your view:
<table style="border-collapse:separate; border-spacing:0px 10px;">
<thead>
<tr>
<th>No. </th>
<th>PictureName</th>
</tr>
</thead>
<tbody>
<tr ng-click="change()" ng-repeat="d in data">
<td> {{ d.key }} </td>
<td><a> {{ d.picture }} </a></td>
</tr>
</tbody>
</table>
You can still do it, if you insist on getting table from database. Here what you need to do.
-Run angular digest cycle again manually. After your table loading.
Below is the code:-
$timeout(function () {
var injector = $('[ng-app]').injector();
var $compile = injector.get('$compile');
var $rootScope = injector.get('$rootScope');
$compile(this.$el)($rootScope);
$rootScope.$digest();
},0);
$timeout with time 0 will run digest cycle right.
But i'll personally suggest #davidkonrad answer.
I am trying to populate a html table based on a select box (with staff numbers) changing. The data is being retrieved from a mysql database. I then want to highlight a row when it is hovered over using jquery.
Am I going about this the right way?
main.php
<div id="logHistory">
<label id="historyTableLabel">Your Log History</label>
<table id="logTable">
<tr id="headers">
<td>Log Date</td>
<td>LogType</td>
<td>Start Time</td>
<td>End Time</td>
<td>Duration</td>
</tr>
</table>
</div>
select.php
$staffNum = isset($_POST['staffNumber']) ? $_POST['staffNumber'] : 0;
if($staffNum > 0)
{
populateLogHistory($con, $staffNum);
}
function populateLogHistory($con, $staffNum)
{
//Retrieve data from entries table
$result = mysqli_query($con, "SELECT EntryID, LogDate, LogType, StartTime, StartDate, FinishTime, FinishDate FROM Entries WHERE StaffNumber=$staffNum");
while($row = mysqli_fetch_array($result))
{
$entryID = $row['EntryID'];
$logDate = $row['LogDate'];
$logTypeID = $row['LogType'];
$resulting = mysqli_query($con,"SELECT LogType FROM logType WHERE LogTypeID=$logTypeID");
$logTypeStr = mysqli_fetch_array($resulting);
$startDate = $row['StartDate'];
$startTime = $row['StartTime'];
$start = $startDate . " " . $startTime;
$start = new DateTime($start);
$finishDate = $row['FinishDate'];
$finishTime = $row['FinishTime'];
$finish = $finishDate . " " . $finishTime;
$finish = new DateTime($finish);
$duration = $start->diff($finish);
echo "<tr id=".$entryID.">";
echo "<td>".$logDate."</td>";
echo "<td>".$logTypeStr[0]."</td>";
echo "<td>".$startTime."</td>";
echo "<td>".$finishTime."</td>";
echo "<td>".$duration->h."hr ".$duration->i."</td>";
echo "</tr>";
}
}
jquery code
$(document).ready(function()
{
$("#staffMember").change(function()
{
//Check the mandatory first
var selectedIndex = $("#staffMember").prop('selectedIndex');
isMandatory(selectedIndex, $(this));
if(selectedIndex != -1)
{
//If there is a staff number call the select to populate the log history
var staffNum = $("#staffMember").val();
var dataString = 'staffNumber=' + staffNum;
$.ajax({
type: "POST",
url: "select.php",
data: dataString,
cache: false,
success: function(html)
{
$("#logTable").html(html);
}
});
}
}).change();
});
Use this CSS for the hovering part:
.datarow:hover {
background-color: #ccc;
}
Assuming that you put a class tag to your populated row:
echo '<tr id="'.$entryID.'" class="datarow">';
For the populating part, use .on() for every call so you can still do another call on Javascript DOM elements.
$(document).on("change", "#staffMember", function(){
And if you want to do another event handler on the populated data, let's put it as a class tag instead and the data ($entryID) will be on another data tag.
echo '<tr data-artid="'.$entryID.'" class="datarow">';
So when you try to call it, you can just do:
$(document).on("click", ".datarow", function(){
var entryid = $(this).attr('data-artid'); /* ENTRY ID OF THE CLICKED ROW */
i'm still fresh in using AJAX and i'm having hard time with it.can you please help me with this? i actually have a dropdown and when i select an item in that dropdown a table of queries should print to the tbody.here's my code:
the PHP code:
<select id="proj_id" name="proj_id" onchange="myFunction(this.value)">
<option value="none">---select project---</option>
<?php
//Projects
$r = #mysql_query("SELECT `proj_id`, `proj_name` FROM `projects`");
while($rows = mysql_fetch_assoc($r)) {
$proj_id = $rows['proj_id'];
$proj_name = $rows['proj_name'];
echo '<option value='.$proj_id.'>'.$proj_name.'</option>';
}
?>
</select>
<table>
<thead>
<tr>
<th>Project Name</th>
<th>Material Name</th>
<th>Quantity</th>
<th>Status</th>
</tr>
</thead>
<tbody id="project_estmat">
<?php
//Display Requests
$r = #mysql_query("SELECT `proj_name`, `mat_name`, `req_qty`, `stat_desc` FROM `requests` JOIN `projects` USING(`proj_id`) JOIN `materials` USING(`mat_id`) JOIN `status` ON(requests.stat_id = status.stat_id)");
while ($row = mysql_fetch_array($r)) {
echo '<tr>';
echo '<td>'.$row['proj_name'].'</td>';
echo '<td>'.$row['mat_name'].'</td>';
echo '<td>'.$row['req_qty'].'</td>';
echo '<td>'.$row['stat_desc'].'</td>';
echo '</tr>';
}
?>
</tbody>
</table>
jS CODE:
function myFunction(value){
if(value!="none")
{
$.ajax(
{
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
success: function(data) {
$('#project_estmat').html(data);
}
});
}
else
{
$('#project_estmat').html("select an item");
}
}
and I have this PHP code that should be in the #project_estmat which is a table. And I think this is where the problem lies. Because everytime I select an item, nothing is printing in the table. It shows empty data.
<?php
if (isset($_POST['proj_id'])) {
$r = #mysql_query("SELECT `proj_name`, `mat_name`, `req_qty`, `stat_desc` FROM `requests` JOIN `projects` USING(`proj_id`) JOIN `materials` USING(`mat_id`) JOIN `status` ON(requests.stat_id = status.stat_id)");
if($r){
while ($row = mysql_fetch_array($r)) {
echo '<tr>';
echo '<td>'.$row['proj_name'].'</td>';
echo '<td>'.$row['mat_name'].'</td>';
echo '<td>'.$row['req_qty'].'</td>';
echo '<td>'.$row['stat_desc'].'</td>';
echo '</tr>';
}
}
exit;
}
?>
you have wrapped $.ajax function with, ${
it should be like the following, and try using change, and remove the inline function calling when you do this,
$('#proj_id').change(function() {
var value = $(this).val();
if(value!="none"){
$.ajax({
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
success: function(data) {
$('#project_estmat').html(data);
alert(data);//check whats coming from the server side
}
});
}
});
tested out with a simplified php code to the server end such as the following,
<?php
if (isset($_POST['proj_id'])) {
echo '<tr>';
echo '<td>A</td>';
echo '<td>B</td>';
echo '<td>C</td>';
echo '<td>D</td>';
echo '</tr>';
}
?>
everything looks fine except you have a '$' extra in your if condition
if(value!="none")
${ //here
removing the '$' sign should work...
You shouldn't use the function mysql_query since its deprecated as of PHP 5.5.0 and will be removed (http://php.net/manual/en/function.mysql-query.php). You better use the PHP PDO class (http://php.net/manual/en/book.pdo.php).
Dont suppress your error using '#' error_compression operator. Remove the # symbol from mysql_query and try debugging your code.
Try building a string and sending it back.
$str = '';
if($r){
while ($row = mysql_fetch_array($r)) {
$str .= '<tr>';
$str .= '<td>'.$row['proj_name'].'</td>';
$str .= '<td>'.$row['mat_name'].'</td>';
$str .= '<td>'.$row['req_qty'].'</td>';
$str .= '<td>'.$row['stat_desc'].'</td>';
$str .= '</tr>';
}
return $str;
}
Then when the loop is done we can send the string back. While the dataType property .ajax() uses intelligent parsing to decide what type of data is being sent back and how to construct the returned object, you should just declare it.
$.ajax({
type: "POST",
url: 'content/admin/requests.php',
data: { proj_id: value},
dataType:'html',
success: function(data) {
$('#project_estmat').html(data);
}
});
I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.