DataTables fails to load ajax data source objects - javascript

I want to do this: https://datatables.net/examples/ajax/objects.html
So I have following response.php code:
<?php
include_once("info.php");
$sql = "SELECT * FROM table1";
$result = mysqli_query($link, $sql);
$amparray = array();
while($row = mysqli_fetch_assoc($result)){
$emparray['data'][] = $row;
}
header('Content-Type: application/json');
echo json_encode($emparray);
mysqli_close($link);
/*
The output will be of the form:
{"data": [{"id":"1","Name":"Test1","URL":"test1.com","Language":"English","Number":"5165489"},{"id":"2","Name":"Test2","URL":"test2.com","Language":"English","Number":"4747489"}]}
*/
?>
and my index.php code:
<html>
<head>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable( {
"ajax": {
"url": "response.php"
},
"columns": [
{ "data": "Name" },
{ "data": "URL" },
{ "data": "Number" },
{ "data": "Language" }
]
} );
} );
</script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>URL</th>
<th>Number</th>
<th>Language</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>URL</th>
<th>Number</th>
<th>Language</th>
</tr>
</tfoot>
</table>
</body>
</html>
According to JSONLint my JSON output from response.php is valid and the same as wanted on datatables.net example. Even if I download the output and save as data.txt and use
"ajax": {"url": "data.txt"},
It still doesn't work. It just loads no data: No data avaiable in table.
*Edit in index.php HostName->Name //just a misstype in posting here-

Solved, the code I posted above now normally works. I have no idea why it didn't worked and now it works - probably some mistake like space was not space but some symbol - I just copied and pasted the code and now it works. Strange -.-

Related

Do you see any issues with this GetData script for SharePoint?

I have included the JS and HTML script to see if anyone may see issues with these scripts? They are for a SharePoint list and both files are stored in a site asset library.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="/SiteAssets/GetData.js"></script>
<!--External js file to get data from SharePoint List -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.jqueryui.min.css">
</head>
<body>
<div>
<table id="table_id" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Joining Date</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Joining Date</th>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
<!--GetData JS script below-->
function loadItems() {
var siteUrl = _spPageContextInfo.siteAbsoluteUrl;
var oDataUrl = siteUrl + "/_api/web/lists/getbytitle('EmployeeInfoTest')
/items?$select=Title,Position,Office,Age,Joining_x0020_Date";
$.ajax({
url: oDataUrl,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
try {
$('#table_id').DataTable({
"aaData": data.d.results,
"aoColumns": [
{
"mData": "Title"
},
{
"mData": "Position"
},
{
"mData": "Office"
},
{
"mData": "Age"
},
{
"mData": "Joining_x0020_Date"
}
]
});
} catch (e) {
alert(e.message);
}
}
function myErrHandler(data, errMessage) {
alert("Error: " + errMessage);
}
The first portion is the HTML page, and then the second part of the script is the JS. I have commented out where the JS script starts.
Here is the output I get in SharePoint-image below:
GetData output error
well error is hard to find but still u have missed out few steps when starting with js
this link i have sent will help u out
https://www.c-sharpcorner.com/article/using-jquery-datatable-to-display-sharepoint-list-data-on-share/
I didn't find where you call the function loadItems, I load SharePoint list data after DOM ready usually as _spPageContextInfo depends on SharePoint JS libraries init(so _spPageContextInfo may not init correctly if you use it if you not delay your rest request ).
Sample demo:
<table id="example" class="wpDataTable" style="width:100%">
<thead>
<tr>
<th></th>
<th>Title</th>
<th>City</th>
<th>TestNumber</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Title</th>
<th>City</th>
<th>TestNumber</th>
</tr>
</tfoot>
</table>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('listtitle')/items?$select=Title,City,TestNumber&$orderby=Created",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (result) {
_Data = result.d.results;
$('#example').DataTable({
columns: [
{ "data": "Title" },
{ "data": "City" },
{ "data": "TestNumber" }
],
data: _Data,
"displayLength": 25
})
},
error: function (error) {
console.log(JSON.stringify(error));
}
})
})
</script>

Why is datatable cdn not working on table generated from ajax?

The datatable cdn is not working with a table that I call from another page using ajax. The new table gets generated, but it does not show the other features of the datatable in the table, and only show table on the page.
I have made a page which has a button, which calls a function that refreshes the table by ajax. I put the cdn datatable links and codes on the other page which is working fine when opened directly, but when called from ajax it doesn't show the datatable cdn function. Instead, the whole table is shown.
$(function() {
$('#populate').click(function() {
$.ajax
({
type: "POST",
url: "getPurchaseInvoice.php",
data: $('#frm3').serialize(),
success: function(data)
{
$('.example').html(data);
}
});
});
});
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href=" https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table style="width:100%" border="1" class="example" data-page-length="25">
<thead>
<tr>
<th>S.No</th>
<th>Invoice No.</th>
<th>Date</th>
<th>Name</th>
<th>Total Amount</th>
<th>Action</th>
</tr>
</thead>
<tbody>
while($row = mysql_fetch_assoc($rs)){
?>
<tr>
<td><?php echo $inc;?></td>
<td><?php echo $row['hrm_inv_no'];?></td>
<td><?php echo $row['fdate'];?></td>
<td><?php if($row['hrm_vendor_name'] != ''){ echo $row['hrm_vendor_name']; } else { echo "Other"; }?></td>
<?php /*?><td><?php echo $row['hrm_vendor_name'];?></td><?php */?>
<td><?php echo $row['hrm_net_value'];?></td>
<td align="center"><a class="iframef" href="purchaseinvoice.php?actiontype=print&id=<?php echo $row['hrm_inv_no'];?>"><img src="images/print.png" alt="Print"></a> | <img id="itemdel" title="Delete" onclick="deletePos('<?php echo $row['hrm_inv_no'];?>')" src="images/b_drop.png" style="cursor:pointer" alt="Delete"></td>
</tr>
<?php $inc++;
}
/*header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Purchase-Invoice-".date('Y-m-d').".xls");
header("Pragma: no-cache");
header("Expires: 0");
*/
?>
</tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.flash.min.js"></script>
<script type="text/javascript" src="tableexport/jszip.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.32/vfs_fonts.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.html5.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/buttons/1.5.1/js/buttons.print.min.js"></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
$(document).ready(function() {
$('table.example').DataTable( {
dom: 'lBfrtip',
buttons: [
{
extend: 'excelHtml5',
text: 'Save Excel',
title: 'Purchase Invoice',
customize: function( xlsx ) {
var sheet = xlsx.xl.worksheets['sheet1.xml'];
$('row:first c', sheet).attr( 's', '42' );
}
},
{
extend: 'pdfHtml5',
text: 'Save Pdf',
title: 'Purchase Invoice'
}
]
} );
} );
</script>
<div id="purchaseInvoice">
<table style="width:100%" border="1" class="example" data-page-length="25">
<thead>
<tr>
<th>S.No</th>
<th>Invoice No.</th>
<th>Date</th>
<th>Name</th>
<th>Total Amount</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
If my understanding is good, you would like to load a php page containing a Datatable providing some data.
If so, the .load() method should be appropriate.
$('.example').load( "getPurchaseInvoice.php", $('#frm3').serialize());

how do i populate a jquery datatable from php without configuring e table forrver side processing

I want to populate a datatable from a php call in my $(document).ready function, but I don't want to configure the table for server side processing (I want subsequent sorting/filtering/sorting to happen client side). Below is my current code. Note: I ran the php On the server and pasted the output into a text file. If I use the path to the text file as my url, I get the intended result. So I think that datatables is trying to read my php file as json, and, of course failing. How do I get it to use the output from the php file instead of the php file itself?
Code:
<html>
<head>
<title>NCompass Failed Fax Monitor</title>
<link rel="stylesheet" type="text/css" href="jQuery/datatables.min.css"></link>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#faxList').DataTable({
ajax: {
url: 'php/Data.php',
dataSrc: 'transactions'
},
columns: [
{ data: 'PROCESS_DATE' },
{ data: 'PROCESS_STATUS' },
{ data: 'PDF_FILE_NAME' },
{ data: 'REF_ID' },
{ data: 'ADDITIONAL_INFO' }
]
});
});
</script>
</head>
<body>
<h2>NCompass Failed Fax Monitor</h2>
<br>
<table width="100%" class="display" cellspacing="0" id="faxList">
<thead>
<tr>
<th>Process Date</th>
<th>Status</th>
<th>PDF File</th>
<th>Reference ID</th>
<th>Error Description</th>
</tr>
</thead>
</table>
</body>
</html>

How to pass JavaScript data to jQuery DataTables

I'm very frustrated trying to insert and show a JSON within a table. I'm using jQuery DataTable to do it.
I have the following jQuery and HTML code but without success:
<table id="sectorsTable">
<thead>
<tr>
<th><b>Numero</b></th>
<th><b>Nombre</b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var jsonArray = { layersSelected: temporaryArraySectors };
var jsonString = JSON.stringify(jsonArray, null, 2);
$('#sectorsTable').dataTable({
'ajax': jsonString
});
</script>
By the way, the content of the vars is:
temporaryArraySectors = [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ];
jsonString = '{"layersSelected": [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ] }';
What is wrong?
You don't need to create JSON string with JSON.stringify, just set data option equal to temporaryArraySectors.
See example below for code and demonstration.
$(document).ready(function() {
var temporaryArraySectors = [ [19,"Cordillera"], [10,"Guaiquillo"], [34,"Zapallar"], [27,"Rural Poniente"], [1,"Aguas Negras"], [24,"La Obra"], [28,"Rural Sur"] ];
var table = $('#sectorsTable').DataTable({
data: temporaryArraySectors
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>
</head>
<body>
<table id="sectorsTable" class="display">
<thead>
<tr>
<th><b>Numero</b></th>
<th><b>Nombre</b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>

How can i call SQL query and load it to DATATABLE plugin using CodeIgniter and jquery?

I hope you can help me. My problem is I want to load a huge amount of data total of 50000 rows in my datatable plugin but I dont know how to incorporate it with CodeIgniter framework.
Here's my sample data.
In my controller i create a function like this, for testing purposes I didn't put it in my model.
public function displayListItem(){
$sqlSelectAll = "select * from items";
$resultSelectAll = $this->db->query($sqlSelectAll);
echo json_encode($resultSelectAll->row_array());
}
Next is my view to call the SQL:
<!-- jquery part -->
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "<?php echo site_url("item_controller/displayListItem"); ?>"
} );
} );
Below is my table that will populate my data from mysql database
<table id="example">
<thead>
<tr>
<th></th>
<th>CODE</th>
<th>NAME</th>
<th>DESCRIPTION</th>
<th>BRAND</th>
<th>UNIT</th>
<th>CATEGORY NAME</th>
<th>ENTRY DATE</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<!-- THIS IS THE PART WHERE I NEED TO PUT THE DATA, BUT I DON'T KNOW HOW -->
</tbody>
</table>
That's all guys I hope you can help me. Thanks
Firstly keep the media folder in the codeigniter project folder. media folder is one which is required by datatables which contains the js,images and css files. set your base_url in codeigniter config.php. setup your database in codeigniter database.php. setup your url helper $autoload['helper'] = array('url'); in autoload.php.
This is my controller.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller
{
public function index()
{
$this->load->model('cmodel');
$data['d']=$this->cmodel->get_result();
$this->load->view('welcome_message.php',$data);//$data is an array which is sent to view
}
}
The $data['d'] contains the array returned from the model which is sent to view
This is my model.
<?php
class Cmodel extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get_result()
{
$query=$this->db->query("your custom query;");
return $query->result_array();//return the result_array to the controller.
}
}
?>
This is the view
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> CodeIgniter</title>
<style>
*{
font-family: arial;
}
</style>
<style type="text/css">
#import "<?php echo base_url();?>media/css/demo_table_jui.css";
#import "<?php echo base_url();?>media/themes/smoothness/jquery-ui-1.8.4.custom.css";
</style>
<script src="<?php echo base_url();?>media/js/jquery.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>media/js/jquery.dataTables.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#datatables.dataTables_filter input').focus()
$('#datatables').dataTable({
"sPaginationType":"full_numbers",
"aaSorting":[[2, "desc"]],
"bJQueryUI":true
});
})
</script>
</head>
<body>
<div>
<table id="datatables" class="display">
<thead>
<tr>
<th>id</th> <!-- These are the table heading-->
<th>name</th>
<th>order</th>
</tr>
</thead>
<?php foreach($d as $row):?><!--This is how you access the fields -->
<tr>
<td>
<?php echo $row['id'];?>
</td>
<td>
<?php echo $row['name'];?> <!-- here id,name,order are my column names-->
</td>
<td>
<?php echo $row['order'];?>
</td>
</tr>
<?php endforeach?>
</table>
</div>
</body>
</html>
This will work perfectly. please vote

Categories

Resources