dynamically generated table does not behave as datatable after AJAX call - php

I have dynamically generated table in PHP but in response this table is not being created as datatable even i have used datatable plugin in file.
I have also one table that is generated on the page ready event with same schema and it has datatable behaviour.
so whats problem with dynamically generated table?
Plz Help
Thanks.
My code is as below :
ajax.php
$projectArr=$database->select("odeskuserdetails","OdeskUserId,UserName","IsDeleted=0");
$grand=0;
for($i=0;$i<count($projectArr);$i++){
$query="SELECT count(JobStatusId) as count from jobstatus where CreatedDate BETWEEN '".$_REQUEST['dateFrom']."' AND '".$_REQUEST['dateTo']."' and StatusId=3 and UserId in (SELECT UserId FROM odsekuserassignment where OdeskUserId =".$projectArr[$i]['OdeskUserId'].")";
$result= mysql_query($query);
$row= mysql_fetch_array($result);
$k=$i+1;
$projectArr[$i]['Sr.No.']=$k;
$projectArr[$i]['Total Jobs']=$row['count'];
$grand +=$row['count'];
}
// Sort the array by Total Jobs.
usort($projectArr, function ($a, $b) {
return ($b['Total Jobs'] - $a['Total Jobs']);
});
// Table Creation Starts :
echo '<table id="table2" class="tablesorter table table-bordered table-condensed table-hover table-striped" >
<thead>
<tr>
<th><center>Sr. No.</center></th>
<th><center>Odesk Account</center></th>
<th><center>Total Jobs Applied</center></th>
</tr>
</thead>
<tbody>';
if(is_array($projectArr))
{
$cval='0';
foreach ($projectArr as $data) {
if (!is_array($data)) {
if($cval=='0')
{
$cval ='1';
echo '<tr class="allPrjRow">';
echo '<td><center>'.$projectArr["Sr.No."].' </center></td>';
echo '<td><center>'.$projectArr["UserName"]. '</center></td>';
echo '<td><center>'.$projectArr["Total Jobs"].'</center></td>';
echo '</tr>';
} }
else
{
echo '<tr class="allPrjRow">';
echo '<td><center>'.$data["Sr.No."].'</center></td>';
echo '<td><center>'.$data["UserName"].'</center></td>';
echo '<td><center>'.$data["Total Jobs"].'</center></td>';
echo '</tr>';
}
}
echo '</tr>';
// print_r($x);
}
echo '</tbody>
</table>
<div id="gtotal" style="float: right;margin-right: 200px;">Grand Total :'.$grand.'</div>';

It depends on where you have put your code snippet. Place the code which creates dynamic table at the end,when all the js gets loaded.

Related

Return instead of echo in WP plugin

This is probably a stupid question, but I'm new to coding so here goes :-).
I'm trying to create a simple plugin for WordPress. The plugin gets data from a MySQL database and echos out a table with the results. My problem is when I use echo the plugin is places first on the page even if i put the shortcode in the middle of the page. I understand that is because I use echo instead of return. I just don't get how to use return in my case. Any help would be much appreciated :-).
Here's my code:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
echo '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
echo '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
echo '</tbody>
</table>';
}
add_shortcode( 'startlist', 'create_startlist' );
You want to assign your output to a variable, instead of echoing:
$get_runners = $connection->prepare('SELECT first_name, last_name, nick_name, FROM database WHERE status = :status ORDER BY first_name ASC');
$get_runners->execute([status=>'success']);
// Create the table
$output = '
<table id="Table" class="start-list-table">
<thead>
<tr class="start-list-tr">
<th scope="col">Name</th>
<th scope="col">Club</th>
</tr>
</thead>
<tbody>
';
// Get the runner object:
$runners = $get_runners->fetchAll();
foreach($runners as $runner){
if($runner->nick_name)
{
$runner_name = $runner->first_name.' "'.$runner->nick_name.'" '.$runner->last_name;
}
else
{
$runner_name = $runner->first_name.' '.$runner->last_name;
}
$output .= '
<tr class="start-list-tr">
<td data-label="Name">'.$runner_name.'</td>
<td data-label="Club">'.$runner->club.'</td>
</tr>';
}
$output .= '</tbody>
</table>';
return $output;
}
add_shortcode( 'startlist', 'create_startlist' );
This uses concatenation to continue to fill the variable through your function. You then set the return to the $output variable.
Firstly read more about Shortcodes Output : https://codex.wordpress.org/Shortcode_API#Output
There are two ways that I can think of at this moment.
Using ob_start... basically you need to wrap you code in ob_start()
function create_startlist() {
ob_start();
/* CODE HERE */
return ob_get_clean();
}
Second is to use a concatenation operator
function create_startlist() {
$output = '';
$output .= 'OUTPUT HERE';
return $output;
}

Dynamically EDIT table data, PHP, AJAX

I am looking for the cleanest way I could do the following.
<?php
function display_data($label, $yes_no, $model) {
$return = "<tr><th><label>".$label."</label></th><td>";
if ($yes_no == '1') { $return .= "Yes"; } else { $return .= "No"; }
$return .= "</td><td>";
if (isset($model)) {
$return .= $model;
}
$return .= "</td></tr>";
return $return;
}
?>
<table>
<thead>
<tr>
<th>Make</th>
<th>Yes/No</th>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
echo display_data("Ford", $car_form["available"], $car_form["avail_model"]);
echo display_data("Honda", $car_form["available"], $car_form["avail_model"]);
?>
</tbody>
</table>
I want to be able to EDIT the body contents of the table by just clicking on any of them, with say jquery. Changing the value and once I click out of it, it saves with AJAX.
So I should be able to click into any of the Yes/No or Model rows and change them. I'm going to have a lot of data, so I am not sure how to do this in large scale. I just don't want to have to create a individual jquery function, and divs for every single piece of data I have. If anyone can think of a cleaner way, that would be awesome.
Everything I have now, is working correctly, I just have not implemented a CRUD like system into this yet.

Updating Table or div Data using Ajax Codeigniter

I am trying to create a page where it shows the current chats done by clients.
Now I am using Openfire as Server, and PHP Ajax for scripting.
Openfire dumps data into MySQL Table.
I retrive all the records using Codeigniter-PHP:
public function get_chats()
{
$this->db->select('*');
$this->db->from('ofMessageArchive');
$query = $this->db->get();
$result = $query->result();
$this->data['messages'] = $result;
$this->data['subview'] = 'dashboard/test';
$this->load->view('_layout_main', $this->data);
}
Now on my view I have table :
<table class="table table-striped table-bordered table-hover" >
<thead>
<th>From</th>
<th>To</th>
<th>Message</th>
<th>Time</th>
</thead>
<tbody>
<?php if(count($messages)): foreach($messages as $key => $message): ?>
<tr>
<td><?php $users = explode("__", $message->fromJID); echo $users[0];?></td>
<td><?php $tousers = explode("__", $message->toJID); echo $tousers[0]; ?></td>
<td><i class="material-icons">play_circle_filled</i>Message</td>
<td><?php echo $date->format('d-m-y H:i:s'); ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
Now I don't want to reload the whole page instead just refresh the table contents every 5 seconds.
I am using DataTables.
I also thought I could pass json to my view, but I don't know how to update it every 5 seconds.
public function get_chats()
{
$this->db->select('*');
$this->db->from('ofMessageArchive');
$query = $this->db->get();
$result = $query->result();
if (count($result)) {
$response = json_encode($result);
}
else
{
$response = false;
}
echo $response;
}
Also this is going to send new and older messages.
So I only want to append news messages to table old message should be not repeated
Your backend function :
public function get_chats()
{
$this->db->select('*');
$this->db->from('ofMessageArchive');
$query = $this->db->get();
$result = $query->result();
if (count($result)>0) {
$response['status']= true;
$response['messages']= $result;
$response['date']= date("d-m-y H:i:s", strtotime($your-date-here));
}
else
{
$response['status']=false;
}
echo json_encode($response);
}
You have to make javascript function like this :
<script>
function myAJAXfunction(){
$.ajax({
url:'your url here',
type:'GET',
dataType:'json',
success:function(response){
console.log(response);
var trHTML='';
if(response.status){
for(var i=0;i<response.messages.length;i++){
users =response.messages[i]fromJID.slice('--');
touser=response.messages[i]toJID.slice('--');
trHTML=trHTML+
'<tr>'+
'<td>'+users[0]+'</td>'+
'<td>'+touser[0]+'</td>'+
'<td><i class="material-icons">play_circle_filled</i>Message</td>'+
'<td>'+response.date+'</td>'+
</tr>';
}
$('tbody').empty();
$('tbody').append(trHTML);
}else{
trHTML='<tr><td colspan="4">NO DATA AVAILABLE</td></tr>';
$('tbody').empty();
$('tbody').append(trHTML);
}
},
error:function(err){
alert("ERROR LOADING DATA");
}
});
}
// calling above ajax function at every 5 seconds
setInterval(myAJAXfunction,5000);
</script>

How to make a table in phpword?

Bellow are my code, i get four column from these, but the result shows every one data will loop in four time in one column then it appear again in new column with the same data.
<?php
$tampil_data = $this->in_elektronik_model->tampil_data(); //load data
foreach ($tampil_data as $tampildata) {
for ($i = 0; $i < 4; $i++) {
$table->addRow(500); //make new row
for ($j = 0; $j < 4; $j++) {
$table->addCell(2000)->addText(htmlspecialchars($tampildata->elektronik_nama)); //content of table
}
}
}
model
function tampil_data() {
$this->db->where('elektronik_status_aktif', 0);
$tampil = $this->db->get('in_elektronik');
if ($tampil->num_rows() > 0) {
return $tampil->result();
} else {
return array();
}
}
How to make table with four column, where the content of table will appear from right column to left and appear just one data in one time, after four column are full, it makes new row?
You can refer this code. This is the way i have done table in view page
<table border="1">
<tr role="row">
<th width="5%">Featured Id</th>
</tr>
<?php
if(!empty($results))
{
foreach ($results as $row) {
?><tr>
<td class=" "><?php echo $row->fet_id; ?></td>
</tr>
<?php }}
?>
</table>

Hide column if column is empty i.e. array element is empty

I have an array such:
$prices = array();
Along with a MySQL query and fetch:
$query = "SELECT $columns FROM Prices WHERE `key` LIKE '$rows' LIKE '$AirportPU' AND rate LIKE '$rate'";
if($results = $db->query($query))
{
if($results->num_rows)
{
while($row = $results->fetch_object())
{
$prices[] = $row;
}
$results->free();
}
I've printed out the table using the following code: (I have removed some table columns)
<?php
if(!count($prices)) {
echo '<p>No results found for your current search. Use the inputs to the left to change the filters.</p>';
} else {
?>
<table>
<thead>
<tr>
<th>Location</th>
<th>City</th>
</tr>
</thead>
<tbody>
<?php
foreach ($prices as $p) {
?>
<tr>
<td> <?php echo $p->Location; ?> </td>
<td> £<?php echo $p->City; ?> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php } ?>
I can return data from the MySQL query, and print this to the table. However, sometimes not all the columns need be printed as they have no values. I would like to hide these columns.
I have tried checking the array using:
print (isset($prices["City"])) ? "Exists</br>" : "Doesn't Exist</br>" ;
But that always returns "Doesn't Exist"
if (array_key_exists("City",$prices))
{
echo "Element exists!";
}
else
{
echo "Element does not exist!";
}
That also returns false.
You need to check it inside the foreach loop which you are executing.
print (isset($p->City)) ? "Exists</br>" : "Doesn't Exist</br>" ;
Check with
if(empty($price['City'] || $price['City'] == "")){
//Hide column
}

Categories