Jquery Datatables Parent Child data - php

I'm working with this Datatables Demo to display child rows. And i'm using php to return an array or data. I have it functioning pretty well, but have a few issues.
Here is an image of what I have currently.
As you see in the picture, there are two parent rows with the same question, and the child rows with different answers.
1. I need a way to limit one parent row for each distinct question.
2. I also need a way to loop through and display multiple child rows in the same child table.
3. Another option is how to assign data to the parent rows and another set of data to the child rows.
I know I should do that in my query, but the question column is single to many results, in two separate tables. The only way to do it with queries would be to return one result for the questions and then make another ajax call to fill the child rows. I was assuming this would be easier.
CODE:
Table:
<table id="car" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="details-control" style="max-width: 80px;">Expand</th>
<th>Question</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th></th>
<th>Question</th>
</tr>
</tfoot>
</table>
Script:
function format(d) {
//d is the original data object for the row
var tbl = '<table cellpadding="5" cellspacing="0" border="0" style="margin-left:110px; width:100%; font-size:12px;">' +
'<tr>' +
'<th style="width:60%; color:3383bb;">Answer Choices</th>' +
'<th style="width:15%; color:3383bb;"># of Answers</th>' +
'<th style="width:15%; color:3383bb;">Percentage</th>' +
'</tr>' + '<tr>' +
'<td>' + d.Answer + '</td>' +
'<td>' + d.NumberOfAnswers + '</td>' +
'<td>' + d.Percent + '</td>' +
'</tr>' + '</table>';
return tbl;
}
var table2 = $('#car').DataTable({
"ajax": "/rmsicorp/clientsite/reset/survey/surveyajax.php",
"scrollY": "400px",
"paging": false,
"bAutoWidth": true,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "Question" },
],
}).columns.adjust().draw();
Query result:
The question column is just repeating for each answer. The rest of the columns are distinct.

It's a common problem, you can solve it on query side or language side. With this scenario i prefer the language side. What you can try to do:
Order you query by Question text;
Check if last and actual Question have the same text;
If so, add the answer to actual Question;
Otherwise create a new Question entry.
You will have to edit you format function to do that, i can suggest you to split it in two parts, one with Question header and one with the data of answers, and then you control: render or not the header.

Related

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

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);

append with ajax call on table not clearing previous data in jquery php?

I am working with jquery and php to get dynamic data with ajax call
into table format. I have one select option where i can choose
different companies.Onselect i will get some data of particular
employee with ajax i am binding that data to table. But problem is if
i choose company 1 then i can able to bind data of company 1. onchange
company 2 data of company 1 should be disappear and company 2's data
only be there. but in my condition onchange company 2 previous data is
still there.
Below is my ajax call code:
$.ajax({
method: "GET",
dataType: 'json',
url:"getdata.php?id="+emp_id,
success:function (response){
$.each(response, function( index, value ) {
$("table.table").append("<tr><td>" + response.emp_name + "</td><td>" + "</td><td><input type='file'></td></tr>");
});
},
});
Below is my html:
<table class="table">
<thead>
<tr>
<th>Employee Name</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
since you use append on success of getting data, you must clear the data on your table or else it will only add data below.
ON YOUR HTML
Set attr id to your <tbody> tag:
<tbody = "bodytable">
ON YOUR SCRIPT
add code to clear the data on your <tbody>
$("bodytable").empty();
$.each(response, function( index, value ) {
$("table.table").append("<tr><td>" + response.emp_name + "</td><td>" + "</td><td><input type='file'></td></tr>");
});
There are many ways to do that. Hope this helps!
You should empty your table first before appending content. Like below:
success:function (response){
$("table.table").find('tbody').empty();
$.each(response, function( index, value ) {
$("table.table").find('tbody').append("<tr><td>" + response.emp_name + "</td><td>" + "</td> <td><input type='file'></td></tr>");
});
}.
Also you should append in table tbody. Hope it helps you.

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);
}
});
}

JSON array to an HTML table and display the data inside td tag

I have json array return as bellow
{"id":16,"minutes":146}
{"id":17,"minutes":137}
{"id":18,"minutes":123}
{"id":22,"minutes":84}
I'm trying to render above json array inside table tbody td which json array id's equal to td id's and display the minutes inside td tag
for example json id :16 minute:146 and display it in <td id="16">146</td>
<table>
<thead>
<tr>
<th>op</th>
<th>Minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td>op1</td>
<td id="16">0</td>
</tr>
<tr>
<td>op2</td>
<td id="17">0</td>
</tr>
<tr>
<td>op3</td>
<td id="18">0</td>
</tr>
<!--....and goes on -->
</tbody>
</table>
js
$.ajax({ url: statUrl, type: 'POST',
data: {
begin: begin,
end: end
},
success: function(data){
}
});
Your JSON is invalid it should only represent one object, a valid version of what you have will be
[{"id":16,"minutes":146},
{"id":17,"minutes":137},
{"id":18,"minutes":123},
{"id":22,"minutes":84}]
If your data IDs directly correspond to already existing DOM element IDs then it should be rather easy:
for (var i = 0; i < data.length; i++) {
$('#' + data[i].id).text(data[i].minutes);
}
This is using jQuery ofc.
you can use json_decode($json, true) in php to convert the json to an array then loop over it's elements and build your table.
If you want to do it client side, I think you must create table, tr and td elements manually and populate them. ExtJS has ready grid for this.
Server side is easier.
I created a jsFiddle here: http://jsfiddle.net/5pKjW/11/
As Musa stated, the JSON you posted is not valid, it should be an array containing all the objects.
The code following is basically what you need to do inside the success callback, just use data instead of result.
What I do is creating a table, appending a row for every element of the array and then appending the whole table to an element of the DOM.
var result = [{"id":16,"minutes":146},{"id":17,"minutes":137},{"id":18,"minutes":123},{"id":22,"minutes":84}];
var $table = $('<table><thead><tr><th>op</th><th>Minutes</th></tr></thead>'),
$tbody = $('<tbody>').appendTo($table),
i;
for (i = 0; i < result.length; i++){
$tbody.append('<tr><td>op' + (i+1) + '</td><td id="' + result[i].id + '">0</td></tr>');
}
$table.appendTo('#container');
As T.J. Crowder commented, a valid HTML4 id attribute can't start with a digit. If I were you, I would prefix it with a string (<td id="prefix' + result[i].id + '">0</td>).
MrOBrian suggested to use a rendering engine. Maybe for a simple case like this, and if you don't need a rendering engine elsewhere, it's an overkill, but that's absolutely something worth considering, if you need something more complicated in the future.
as suggested fixed json array to
{
"25":72.3833,
"17":116.3167,
"16":25.75,
"34":28.3333,
"29":136.8831,
"19":40.9166,
"32":43.6,
"22":83.9001
}
and js
$.getJSON(statUrl, {begin: begin, end: end}, function(data) {
$.each(data, function(key, val) {
$('#op_' + key).text(Math.ceil(val));//also fixed td id
});
});
so got the result as expected.
thanks for your time.

Categories