Json object through Ajax to Html Datatable - javascript

I have a PHP code that returns a JSON object which is actually an array of data , and i want to display the JSON content on a datatable but i have been getting this error :
DataTables warning: table id=example - Invalid JSON response
PHP , HTML and JS are below , any help is appreciated , thank you.
PHP :
<?php
include "../config.php";
$db = config::getConnexion();
$sql = "SELECT * FROM produits";
$req = $db->prepare($sql);
$req->execute();
$liste = $req->fetchAll();
//Convert Array to JSON Obj
$someJSON = json_encode($liste);
echo $someJSON;
//var_dump($someJSON);
?>
HTML :
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>nom</th>
<th>num</th>
<th>prix</th>
<th>qte</th>
<th>cat</th>
<th>desc</th>
</tr>
</thead>
<tbody>
<tr>
<tr>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
<td ></td>
</tr>
</tbody>
<tfoot>
<tr>
<th>nom</th>
<th>num</th>
<th>prix</th>
<th>qte</th>
<th>cat</th>
<th>desc</th>
</tr>
</tfoot>
</table>
Javascript :
<script type="text/javascript">
$(document).ready(function() {
$("#example").DataTable({
ajax: {
url: "TestAjax.php",
dataSrc: ""
},
columns: [
{ data: "nom" },
{ data: "num" },
{ data: "prix" },
{ data: "qte" },
{ data: "descr" },
{ data: "cat" }
],
iDisplayLength: 1,
iDisplayStart: 0
});
});;
</script>
JSON data :
[{"nom":"chaise1236","0":"chaise1236","num":"1231564658","1":"1231564658","prix":"800","2":"800","qte":"80","3":"80","descr":"description","4":"description","cat":"Interieur","5":"Interieur"},{"nom":"lilyouss","0":"lilyouss","num":"1231564672","1":"1231564672","prix":"5000","2":"5000","qte":"500","3":"500","descr":"youss","4":"youss","cat":"Exterieur","5":"Exterieur"},{"nom":"chaise125","0":"chaise125","num":"1231564660","1":"1231564660","prix":"500","2":"500","qte":"125","3":"125","descr":"descrchaise125","4":"descrchaise125","cat":"Exterieur","5":"Exterieur"},{"nom":"chaise3","0":"chaise3","num":"1231564661","1":"1231564661","prix":"125","2":"125","qte":"500","3":"500","descr":"descr3","4":"descr3","cat":"Interieur","5":"Interieur"},{"nom":"chaise5","0":"chaise5","num":"1231564662","1":"1231564662","prix":"1256","2":"1256","qte":"500","3":"500","descr":"descr55","4":"descr55","cat":"Exterieur","5":"Exterieur"},{"nom":"Fauteuil","0":"Fauteuil","num":"1231564663","1":"1231564663","prix":"550","2":"550","qte":"0","3":"0","descr":"Fauteuil Comfort","4":"Fauteuil Comfort","cat":"Interieur","5":"Interieur"},{"nom":"Fauteuil 2 Places","0":"Fauteuil 2 Places","num":"1231564664","1":"1231564664","prix":"2500","2":"2500","qte":"32","3":"32","descr":"faut Comfortable","4":"faut Comfortable","cat":"Interieur","5":"Interieur"},{"nom":"Tableau Artistique","0":"Tableau Artistique","num":"1231564665","1":"1231564665","prix":"5000","2":"5000","qte":"0","3":"0","descr":"tableau","4":"tableau","cat":"Interieur","5":"Interieur"},{"nom":"Table","0":"Table","num":"1231564667","1":"1231564667","prix":"230","2":"230","qte":"200","3":"200","descr":"Tbmx","4":"Tbmx","cat":"Interieur","5":"Interieur"},{"nom":"AspirateurAS","0":"AspirateurAS","num":"1231564668","1":"1231564668","prix":"125","2":"125","qte":"500","3":"500","descr":"Aspirateur Samsung","4":"Aspirateur Samsung","cat":"Interieur","5":"Interieur"},{"nom":"TableTs","0":"TableTs","num":"1231564669","1":"1231564669","prix":"500","2":"500","qte":"250","3":"250","descr":"Descr","4":"Descr","cat":"Interieur","5":"Interieur"},{"nom":"Prodtest","0":"Prodtest","num":"1231564671","1":"1231564671","prix":"500","2":"500","qte":"500","3":"500","descr":"description test","4":"description test","cat":"Interieur","5":"Interieur"}]

Related

Datatables not showing my data but after applying filter

I am populating a table via Ajax JSON with datatables, this is my JS code:
$(document).ready(function () {
$.ajax({
url: "../WebService.asmx/LoadUsers",
type: 'POST',
datatype: 'json',
//content: 'json', lo mismo que arriba
contentType: 'application/json; charset=utf-8',
success: function (data) {
var datos = JSON.parse(data.d);
// METODO JQUERY DATATABLES Documentación
$('#tblUsers').DataTable({
data: datos,
columns: [
{ 'data': 'id' },
{ 'data': 'username' },
{ 'data': 'password' },
{ 'data': 'dregistered' },
{
'data': null,
'defaultContent': "<img src='../assets/img/delete.png' id='btnDel' style='width: 22px; cursor:pointer;' />"
}
//
],
responsive: true
});
/*DataTables instantiation.*/
/*$("#tblUsers").DataTable();*/
},
error: function () {
alert('Fail!');
}
});
});
Html table:
<table id="tblUsers" class="table table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
</tr>
</tfoot>
</table>
My table after loading html page
Is not showing data, it seems like not rendering at first, but after applying column filter or changing entries, the data is showing:
Filtering by entries number
Filtering by column order
Am I missing something? 🤔
Your problem is probably that you are trying to set 5 columns of data (even if the 5th one has data: null) but you have only 4 columns in your HTML <table>.
If you look at your console, probably there should be some error like Cannot read property 'style' of undefined or similar.
So, the loading of the data inside the table is interrupted by the error.
Change your HTML to this (adding an extra <th></th>) and it should go fine:
<table id="tblUsers" class="table table-bordered nowrap" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
<th></th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Usuario</th>
<th>Contraseña</th>
<th>Fecha</th>
<th></th>
</tr>
</tfoot>
</table>

How to display the values from ajax success data to the html table?

I need to view the ajax success message in my html table
my cshtml code is:
#*#{Customer.Models.Customers cust = ViewBag.Customers;
}*#
#{
}
<center><h1 style="color:red">User details</h1></center>
<div>
<table class="table">
<tr>
<td>ID</td>
<td>res.Id</td>
</tr>
<tr>
<td>FIRST NAME</td>
<td>res.Fname</td>
</tr>
<tr>
<td>LAST NAME</td>
<td>res.Lname</td>
</tr>
<tr>
<td>LOCATION</td>
<td>res.Location</td>
</tr>
<tr>
<td>Contact</td>
<td>res.Contact</td>
</tr>
<tr>
<td>Email</td>
<td>res.Email</td>
</tr>
<tr>
<td>Password</td>
<td>res.Password</td>
</tr>
<tr>
<td>Role</td>
<td>res.Category</td>
</tr>
<tr>
</table>
</div>
#section Scripts{
<script>
$.ajax({
contentType: "application/json",
type: "GET",
url: "https://localhost:44397/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
res = data;
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
$("#postResult").val(jqXHR.statusText);
}
});
</script>
}
Is there any way to use the success data to pass in the each table row?
That is I want the res to store the success data and then pass it to the table fields like res.Fname (eg) and it should display the data accordingly.
There are many way you can populate your table through Ajax response. Here the most readable and popular way you could try. See the below code snippet.
<table id="YourTableId" class="table table-bordered table-striped table-responsive table-hover">
<thead>
<tr>
<th align="left" class="yourTableTh">YourProperty</th>
<th align="left" class="yourTableTh">YourProperty2</th>
<th align="left" class="yourTableTh">YourProperty3</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
$.ajax({
contentType: "application/json",
type: "GET",
url: "https://localhost:44397/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
// res = data;
var items = '';
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='yourTableTh'>" + item.YourProperty + "</td>"
+ "<td class='yourTableTh'>" + item.YourProperty2 + "</td>"
+ "<td class='yourTableTh'>" + item.YourProperty3 + "</td>"
+ "</tr>";
$('#YourTableId tbody').append(rows);
});
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
$("#postResult").val(jqXHR.statusText);
}
});
</script>
Another Way Using C# Viewbag:
<table class="table table-bordered">
<thead>
<tr>
<th>Property Header</th>
<th>Property Header</th>
<th>Property Header</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.ViewBagName)
{
<tr>
<td>#item.PropertyName</td>
<td>#item.PropertyName</td>
<td>#item.PropertyName</td>
</tr>
}
</tbody>
</table>
Let me know if you have any additional question.
Hope that would help.
If you need to show value in one column alone then use this type
#*#{Customer.Models.Customers cust = ViewBag.Customers;
}*#
#{
}
<center><h1 style="color:red">User details</h1></center>
<div>
<table class="table">
<tr>
<td>ID</td>
<td id="Id"></td>
</tr>
<tr>
<td>FIRST NAME</td>
<td id="Fname"></td>
</tr>
<tr>
<td>LAST NAME</td>
<td id="Lname"></td>
</tr>
<tr>
<td>LOCATION</td>
<td id="Location"></td>
</tr>
<tr>
<td>Contact</td>
<td id="Contact"></td>
</tr>
<tr>
<td>Email</td>
<td id="Email"></td>
</tr>
<tr>
<td>Password</td>
<td id="Password"></td>
</tr>
<tr>
<td>Role</td>
<td id="Category"></td>
</tr>
<tr>
</table>
</div>
#section Scripts{
<script>
$.ajax({
contentType: "application/json",
type: "GET",
url: "https://localhost:44397/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
res = data;
document.getElementById("Id").innerHTML = res.Id;
document.getElementById("Fname").innerHTML= res.Fname;
document.getElementById("Lname").innerHTML= res.Lname;
document.getElementById("Location").innerHTML= res.Location;
document.getElementById("Contact").innerHTML= res.Contact;
document.getElementById("Email").innerHTML= res.Email;
document.getElementById("Password").innerHTML= res.Password;
document.getElementById("Category").innerHTML= res.Category;
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
$("#postResult").val(jqXHR.statusText);
}
});
</script>
}
I think it will help you :)
You could use Partial view to contain the table data and return PartialViewResult from the api controller ,then show the partial view from the success function of ajax . The following is the steps:
_DetailsPartial
#model DemoTest.Models.User
<center><h1 style="color:red">User details</h1></center>
<div>
<table class="table">
<tr>
<td>ID</td>
<td>#Model.Id</td>
</tr>
<tr>
<td>FIRST NAME</td>
<td>#Model.Fname</td>
</tr>
<tr>
<td>LAST NAME</td>
<td>#Model.Lname</td>
</tr>
<tr>
<td>LOCATION</td>
<td>#Model.Location</td>
</tr>
<tr>
<td>Contact</td>
<td>#Model.Contact</td>
</tr>
<tr>
<td>Email</td>
<td>#Model.Email</td>
</tr>
<tr>
<td>Password</td>
<td>#Model.Password</td>
</tr>
<tr>
<td>Role</td>
<td>#Model.Category</td>
</tr>
<tr>
</table>
</div>
Api controller ,return PartialViewResult
[Route("api/[controller]/[action]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly DemoDbContext _context;
public ValuesController(DemoDbContext context)
{
_context = context;
}
[HttpGet("{id}")]
public async Task<IActionResult> Details(int id)
{
var user = await _context.User.FindAsync(id);
var myViewData = new ViewDataDictionary(new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider(), new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary())
{ { "User", user } };
myViewData.Model = user;
return new PartialViewResult()
{
ViewName= "_DetailsPartial",
ViewData= myViewData
};
}
}
The main view that contains the partial view, use ajax to show the result of success function in the <div id="userdetail"></div>
<div id="userdetail"></div>
#section Scripts{
<script>
var id = 1;
$.ajax({
//contentType: "application/json",
type: "GET",
url: "https://localhost:44343/api/Values/Details/" + id,
success: function (data) {
alert('Welcome!');
$("#userdetail").html(data);
// window.location.href = "/Home/Details/" + data.id;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Failed!');
}
});
</script>
}
Result:
For more details about Partial View , you could refer to the official doc.

Jquery Datatables add new row in json table

I am using: jquery.dataTables.js from: https://datatables.net
I amtrying to add a new row in my json table.
I could not get it work any ideas why not?
jsfiddle: http://jsfiddle.net/f7debwj2/17/
html:
<table id="example" class="display" width="100%" cellspacing="0">
<thead>
<tr>
<th>order</th>
<th>name</th>
<th>country</th>
</tr>
</thead>
</table>
<button id="addRow">Add New Row</button>
<table id="newRow">
<tbody>
<tr>
<td>Line 2
<input type="hidden" value="2" /> </td>
<td>DVap
<input type="hidden" value="DVap" /> </td>
<td>
<input type="text" value="22" /> </td>
</tr>
</tbody>
</table>
jquery:
$(document).ready(function() {
var dt = $('#example').dataTable();
dt.fnDestroy();
});
$(document).ready(function() {
var url = 'http://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
var table = $('#example').DataTable({
ajax: url,
rowReorder: {
dataSrc: 'order',
},
columns: [{
data: 'order'
}, {
data: 'name'
}, {
data: 'place'
}]
});
// add row
$('#addRow').click(function() {
//t.row.add( [1,2,3] ).draw();
var rowHtml = $("#newRow").find("tr")[0].outerHTML
console.log(rowHtml);
dt.row.add($(rowHtml)).draw();
});
});
Like you can see in the documentation you need to change this line:
dt.row.add($(rowHtml)).draw();
to:
table.row.add($(rowHtml)).draw();
The updated fiddle.
Your actual error was
Uncaught ReferenceError: dt is not defined
Just change table.row.add($(rowHtml)).draw() instead of dt.row.add($(rowHtml)).draw() inside button click event.

bootstrap-table-filter-control extension doesn't work in bootstrap-table

I use bootstrap-table and would like to use table-filter-control extension. In this example you can see how to use this extension. When I want to use this extension for more columns, it doesn't work. In my example filter works only for one column.
jsfiddle
html
<table ref="mainTable" class="table table-striped table-bordered table-hover"
cellSpacing="0" id="mainTable" data-show-toggle="true"
data-show-columns="true" data-search="true" data-pagination="true" data-filter-control="true">
<thead>
<tr>
<th data-field="state" data-checkbox="true"></th>
<th data-field="Customer Name" data-sortable="true" data-filter-control="select">Customer Name</th>
<th data-field="Location Type" data-sortable="true">Location Type</th>
<th data-field="Location" data-sortable="true" data-filter-control="select">Location</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Cap Corp</td>
<td>Main</td>
<td>Norwalk CT 06851</td>
</tr>
<tr>
<td></td>
<td>Cap Corp</td>
<td>Other</td>
<td>Norwalk CT 06851</td>
</tr>
<tr>
<td></td>
<td>Tel</td>
<td>Main</td>
<td>Slough SL1 4DX</td>
</tr>
<tr>
<td></td>
<td>Tel</td>
<td>Other</td>
<td>London W1B 5HQ</td>
</tr>
</tbody>
</table>
data-filed should have not spaces, try to change
data-field="Customer Name"
to
data-field="CustomerName"
I updated your jsfiddle and filter-control works.
http://jsfiddle.net/5h595r6g/9/
However it would be great to implement filter options updating to available values, as I described in this post:
bootstrap table filter-control - how to unset unnecessary values from select options
I actually put select2 boxes in the headers, and then used the params feature to pass the code to the server. I made for a much nicer solution. My code isn't with me but if you are interested in it I can pass a sample along Monday.
Edited to add example.
Basic Table
<table id='90day' class='table table-striped' data-filter-control='true'>
<thead>
<tr>
<th></th>
<th><select id='findfield' class='form-control gosearch'><option></option></select></th>
<th><select id='findwellname' class='form-control gosearch'><option></option></select></th>
</tr>
</thead>
</table>
Initialize the select2
$('#90day').on('post-header.bs.table', function () {
$('#findfield').select2({
width: '100%',
placeholder: 'Field',
allowClear: true,
SingleSelection: true,
ajax: {
url: 'selectfield90day.php?active=y',
dataType: 'json',
//delay: 250,
data: function (params) {
$('#findfield').empty();
var d = new Date();
var n = d.getTime();
return {
q: params.term,
n: n
};
},
processResults: function (data) {
return { results: data };
}
}
});
$('#findwellname').select2({
width: '100%',
placeholder: 'Name',
allowClear: true,
ajax: {
url: 'selectwellname90day.php?active=y',
dataType: 'json',
delay: 250,
data: function (params) {
$('#findwellname').empty();
var d = new Date();
var n = d.getTime();
return {
q: params.term,
field: $('#findfield').text(),
pad: $('#findpad').text(),
n: n
};
},
processResults: function (data) {
return {
results: data
};
}
}
});
//refresh on any select2 change
$('.gosearch').on('select2:close', function(){
$('#90day').bootstrapTable('refresh');
});
});
Finally table initialization
$('#90day').bootstrapTable({
url: ...,
columns:[
...
],
queryParams: function(params){
params['field']=$('#findfield').text();
params['well_name']=$('#findwellname').text();
return params;
}
});

Tablesorter with ajax refresh not working with more than one

I'm using jQueryUI tabs that has a table on each page. The tables are sorted by Tablesorter 2.0.
The following code works great when I have a single table undergoing a refresh on a page. If I add a second table w/ a refresh, only the first one updates. Can someone tell me how I can get two tables to be sorted by tablesorter with ajax refreshes of the data?
The reload is run through this JS function:
$(function () {
$(".tsRefresh").tablesorter({
headers: {
'.cbsort': { sorter: 'checkbox' },
'.nosort': { sorter: false, parser: false }
},
theme : 'jui',
headerTemplate : '{content} {icon}',
widgets : ['saveSort', 'uitheme'],
widgetOptions : {
zebra : ["odd", "even"]
}
});
function getBjson() {
var Tid = $('.tsRefresh').data('id');
var Ttable = $('.tsRefresh').data('table');
var Tbody = $('.tsRefresh').find('tbody').attr('id')
$.ajax({
type: "POST",
url: "ajax.php",
data: 'table=' + Ttable +'&id=' + Tid,
success: function(output) {
document.getElementById(Tbody).innerHTML = output;
// update tablesorter cache
$(".tsRefresh").trigger("update");
},
error: function (xhr, ajaxOptions, thrownError) {
$('#messageResponse').fadeIn(500);
$('#messageResponse').addClass('ui-state-error ui-corner-all').removeClass('ui-highlight-error');
$('#messageResponse').text(xhr.status + ' ' + thrownError + ': Something went wrong - check your inputs and try again.');
}
});
}
if( $('.tsRefresh').length) {
var Ttime = $('.tsRefresh').data('time');
var timer = setInterval(getBjson, Ttime);
getBjson();
}
});
The following is the table code:
<div id="tabs-1">
<fieldset>
<table width="100%" id="issue" name="issue" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container1">
</tbody>
</table>
</fieldset>
</div>
<div id="tabs-2">
<fieldset>
<table width="100%" id="my-load" name="my-load" class="tsRefresh" data-id="<?=$item_id?>" data-table="eq-load-me" data-time="10000">
<thead>
<tr class="bold">
<th class="cbsort"><input type="checkbox" class="checkall"> </th>
<th>OAN/ID</th>
<th>Category</th>
<th>Desc</th>
<th>Issued To</th>
<th>SN</th>
</tr>
</thead>
<tbody id="container2">
</tbody>
</table>
</fieldset>
</div>
My PHP script (ajax.php) outputs the following to the tablesorter's table:
<tr class="dialog-hover" data-table="eq-load-item" data-id="<?=$item_id?>">
<td align="center"><input type="checkbox" id="row-<?=$item_id?>" value="<?=$item_id?>"></td>
<td align="center" valign="top"><?=$item_oan?>-<?=$item_id?></td>
<td><?=$item_cat?></td>
<td align="center" valign="top"><?=$item_desc?></td>
<td align="center" valign="top"><?=$issue_name?></td>
<td align="center" valign="top"><?=$item_serial?></td>
</tr>

Categories

Resources