Passing dynamic JSON data to create a HTML table - javascript

I have a function that receives JSON data, it can be any length and contain any number of columns and rows of data.
I have read that jqGrid would be a good jQuery plugin to use for this scenario but I cannot get it to work.
I have the following code to try and get my table to be populated:
//This code is in another section of my web page but the data is valid
//and is populated over a websocket
var ss = $.parseJSON(data);
var theGrid = jQuery("#list1")[0];
theGrid.addJSONData(ss.NewDataSet.SECURITY_GROUPS);
//alert(ss.NewDataSet.SECURITY_GROUPS[0].NAME);
$(document).ready(function() {
jQuery("#list1").jqGrid({
datatype: "local",
height: 250,
multiselect: true,
caption: "Manipulating Array Data"
});
});
<table id="list1"></table>

Maybe give DataTables a try if jqGrid isn't working for you. It's probably my favorite, and super easy to load via JSON as you've described.
Here's how to load from an AJAX source: http://datatables.net/release-datatables/examples/data_sources/ajax.html
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": '../ajax/sources/arrays.txt'
});
});
UPDATE
var columnArr = [];
var valueArr = [];
var data = ss.NewDataSet.SECURITY_GROUPS; //data is your SECURITY_GROUPS object
//Strip the titles off your first array item only since they are all the same.
$.each(data[0], function(key, value) {
columnArr.push({"sTitle" : key});
});
$.each(data, function(key, value) {
var innerArr = [];
$.each(value, function(innerKey, innerValue) {
innerArr.push(innerValue);
});
valueArr.push(innerArr);
});
$('#example').dataTable( {
"aaData": valueArr,
"aoColumns": columnArr
});

Related

how to send data checbox from ajax to php

I following this code, I want to send data checxbox to php, but this code only send data one by one. how to I can send data to php as much as select data one time send
$('#lunas').click(function(){
$('#tampilkan tbody input:checked').each(function(){
var id = $(this).closest('tr')[0];
var nosam = id.cells[1].innerHTML;
var unit = id.cells[2].innerHTML;
var blthn = id.cells[8].innerHTML;
var dd = Number(hapusTitik(id.cells[9].innerHTML));
var rp = Number(hapusTitik(id.cells[10].innerHTML));
var tgl = document.getElementById('tgl').value;
$.ajax({
url: 'get/penjualan_simpan.php',
data: {'nosam': nosam, 'unit': unit, 'blthn': blthn, 'dd': dd, 'rp': rp, 'tgl': tgl},
cache: false,
success: function(data){
$('#modalByar').modal('hide');
}
}
});
});
});
});
To achieve this you can use map() to build an array of objects from the checkboxes. You can then provide that array to the data property of the AJAX request. Then in your PHP code you can loop through that array and perform whatever actions you require on the data of each row. Try this:
$('#lunas').on('click', function() {
let data = $('#tampilkan tbody input:checked').map(function() {
let $row = $(this).closest('tr');
return {
nosam: $row.find('td:eq(1)').text(),
unit: $row.find('td:eq(2)').text(),
blthn: $row.find('td:eq(8)').text(),
dd: Number(hapusTitik($row.find('td:eq(9)').text())),
rp: Number(hapusTitik($row.find('td:eq(10)').text())),
tgl: $('#tgl').val()
}
}).get();
$.ajax({
url: 'get/penjualan_simpan.php',
data: data,
cache: false,
success: function(data) {
$('#modalByar').modal('hide');
}
}
});
});
I would also suggest you make this request using the POST verb instead of GET.
Consider the following.
$('#lunas').click(function() {
var myData = [];
$('#tampilkan tbody input:checked').each(function(i, el) {
var row = $(el).closest('tr');
myData.push({
nosam: $("td:eq(1)", row).html(),
unit: $("td:eq(2)", row).html(),
blthn: $("td:eq(8)", row).html(),
dd: Number(hapusTitik($("td:eq(9)", row).html())),
rp: Number(hapusTitik($("td:eq(10)", row).html())),
rgl: $('#tgl').val()
});
});
$.ajax({
url: 'get/penjualan_simpan.php',
method: "post",
data: {
checks: myData
},
cache: false,
success: function(data) {
$('#modalByar').modal('hide');
}
}
});
});
This creates an array and each Row in your table then becomes an entry in the Array. It will be an Array of Objects, with each Object containing that rows details.
When in php, you will then receive a complex posted variable. You can access it like so:
var_export($_POST['checks']);
This should show you all the data that was posted. Each of the Rows and Each of the Cells.

How to make datatable specific column editable?

There are various questions put up on this topic but I do not understand them so can anyone help
here is my js code
$(document).ready(function () {
$('#myModal').toggle();
var List = [];
$.ajax({
url: '/urls/' + id,
type: 'POST',
dataType: "json",
data: 'data',
success: function (data) {
console.log("data length: ", data.length);
console.log("data : ", data);
for (var i = 0; i < data.length; i++) {
var Logs = {};
Logs.Info = data[i].Info;
for (var j = 0; j < Logs.Info.length; j++) {
var emplist = {};
emplist.Name = Logs.Info[j].Name;
emplist.dates = Logs.Info[j].dates;
for (var k = 0; k < emplist.dates.length; k++) {
var datelist = {};
datelist.Name = emplist.Name;
datelist.startDate = emplist.dates[k].startDate;
datelist.endDate = emplist.dates[k].endDate;
List.push(datelist);
}
}
}
emptablee = $('#Table').DataTable({
"data": List,
"columns": [
{"data": "Name"},
{"data": "startDate"},
{"data": "endDate"},
],
destroy: true,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false
});
/*emptablee.destroy();*/
}
});
$("#close").on('click', function () {
$("#myModal").hide();
});
});
There are three columns in the table and I want to make a specific columns cell-like editable and show an input box and get the value edited to send.
For anyone checking this now, I've created a custom example in which you can make any column editable by just sending it in a metadata request from serverside.
here : https://github.com/sinhashubh/datatable-examples
If you want, for example, your startDate column to be editable, you need to init the Datatables like this so you can hit the column by class name:
{"data": "startDate", "className": "editable"},
then, with proper event handling
// Activate an inline edit on click of a table cell
$('#Table').on( 'click', 'tbody td.editable', function (e) {
editor.inline( this );
} );
and initializing Editor you will be good:
editor = new $.fn.dataTable.Editor( {
ajax: "../ajax/handle-data.php", // path to back-end data handling
table: "#Table",
fields: [ {
label: "Start Date:",
name: "startDate"
}
]
} );
Also, don't forget to add this outside of document ready handler because you need it as a global var:
var editor;
Full example here (note that Datatables Editor feature is not free) https://editor.datatables.net/examples/inline-editing/columns.html
You can also code up your own completely free version, which is slightly more complicated, without using Editor, but still using class names so you can trigger on click events for specific columns.

Accessing specific data from csv file and show on html

Having some problems accessing specific data from a csv file. Currently I can see all data in the console but when I try to show a specific data getting undefined. For example in my console I get all data and I want to extract the subtitles and show it on the html in a class score-text.
My console looks like this:
subtitle 1,
name1,65%
name2,65%
name3,65%
name4,65%
total,70%
,
subtitle 2,
name1,65%
name2,65%
name3,65%
name4,65%
total,30%
,
subtitle 3,
name1,65%
name2,65%
name3,65%
name4,65%
total,60%
,
subtitle 4,
name1,65%
name2,65%
name3,65%
name4,65%
total,50%
$.ajax({
url: 'test.csv',
type: "GET",
dataType: "text",
success: function (data) {
var rows = data.split(/\n/);
for (var rowIndex in rows)
{
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
}
}
$(".score-text").each(function( index, value ) {
value.innerHTML = result[columns[2]] = rows[2];
});
}
});
Why don't you try putting the insertion part into the loop?
var columns = rows[rowIndex].split(/,/);
for (var colIndex in columns)
{
var colValue = columns[colIndex].trim();
console.log(colValue);
$(".score-text").append(colValue);
}

Dynamic Javascript sourced data - DataTable

I am using DataTable in my application. My application is not a server hosted one. (I will render the HTML directly in my standalone application. Well, that is a different story.)
Currently I am populating DataTable like below,
$(dataTableSelector).dataTable({
"sDom": 't <f> <i> <p> > ',
"bRetrieve": true,
"aaSorting": [],
"aaData": rows,
"aoColumns": columns,
"oLanguage": {
"sSearch": "",
"sInfo": "_START_ - _END_ Total: _TOTAL_ ",
"sInfoFiltered": "(filtered from _MAX_)"
}
});
Here rows are my entire data, in array of arrays as a Javascript sourced data.
But now my problem is, if the data I am going to render with DataTable is huge, then loading takes longer time.
So I am trying to change the data table similar to server side processing(but please note that I don't have any server. It is just a local HTML page). On clicking next,it should load next only, page data.Till then, it should not load the same.
Say, I have a function in javascript
function loadData(start,end, searchString){
//Function to fetch records from a Table with start and end numbers of records.
//searchString is optional.
//rows= GetDataFromTable(start,end, searchString);
return rows;
}
So, whenever the next or previous button is clicked in the data table, or searched, my javascript method should be called and it should repopulate Datatable. Any ideas?
You can load from a local variable into Datatables on every user interaction by using the ajax option and providing your own custom function. One example of its use is on their site, called "Pipelining data to reduce Ajax calls for paging".
Below is a simple example of slicing and filtering a large array and returning a small set based on the selections made on the Datatable. Note that Datatables sends more parameters which I haven't used, but you should use them to make a proper implementation. Also, it's possible that Datatables sends request.length = -1, but I have not dealt with that either.
JavaScript
var rows;
$(document).ready(function() {
rows = getLongArrayOfData();
$("#example").dataTable({
"columns": [
{"data": "column1", "title": "Column 1"},
{"data": "column2", "title": "Column 2"}
],
"serverSide": true,
"ajax": getRows()
});
});
function getRows() {
return function ( request, drawCallback, settings ) {
var dataFiltered;
var recordsTotal = rows.length;
if (request.search.value !== "") {
dataFiltered = rows.filter(FilterStartsWith(request.search.value));
}
var recordsFiltered =
(dataFiltered === undefined) ? rows.length : dataFiltered.length;
var dataSliced =
(dataFiltered === undefined ? rows : dataFiltered)
.slice(request.start, request.start + request.length);
var returnData = {
draw: request.draw,
recordsTotal: recordsTotal,
recordsFiltered: recordsFiltered,
data: dataSliced
};
drawCallback(returnData);
};
}
function FilterStartsWith(wordToCompare) {
return function(element) {
if (typeof element == "object") {
returnValue = false;
for (var property in element) {
if (element.hasOwnProperty(property)) {
if (startsWith(element[property], wordToCompare)) {
returnValue = true;
break;
}
}
}
return returnValue;
}
return startsWith(element, wordToCompare);
}
}
function startsWith(element, wordToCompare) {
if (typeof element != "string") element = new String(element);
return element.slice(0, wordToCompare.length) == wordToCompare;
}
function getLongArrayOfData() {
var retArr = new Array();
for(i=1; i<=100000; i++) {
retArr.push({column1: i, column2: "abc" + (500+i)});
}
return retArr;
}
HTML
<table id="example">
<thead>
</thead>
<tbody>
</tbody>
</table>

JSON Results To A Drop down List

Hi I am Working On a Web Form..
I Have A combo Box for holding all The Units.
I Have Taken All The units from the Database Using JSON,now i need to Bind All these Units To the drop down List
How can I Do this...?
function getUnitFamily(pack_detl_ID,select) {
//***********************************//
PageMethods.getUnitFamily(pack_detl_ID,
function(result) {
if (result != null) {
custinfo = eval(result);
if (custinfo != null) {
$('#<%=drpUnit.ClientID%> option').remove();
var objSub = document.getElementById('<%=drpUnit.ClientID%>');
$.each(custinfo, function(i, item) {
listOpt = document.createElement("option");
listOpt.value = item[0];
listOpt.text = item[1];
objSub.add(listOpt);
});
alert(select);
document.getElementById('<%= drpUnit.ClientID %>').value = select;
}
}
}, pageMethodError);
With An example can any one explain
A combobox sounds like you are using an ASP.NET control. Of course, you can bind your items to that control in the code behind. If you are doing some AJAX stuff and have a dropdown ( element>) in your page which you want to populate at client side, you might want to take a look at what jQuery has to offer. For example use the AJAX api to retrieve your data and push that data into your dropdown like so:
var options = $("#options");
$.each(result, function() {
options.append($("<option />").val("sometext").text("sometext"));
});
In the past I have used a plugin when working with dropdowns.
http://www.texotela.co.uk/code/jquery/select
Request the JSON data:
//Get the JSON Data
$.getJSON(url, function(json) {
PopulateDropDownFromJson(json, "#element");
});
and then just pass the JSON into a function that uses the plugin above
function PopulateDropDownFromJson(json, element){
$.each(json, function() {
$(element).addOption(this[valueText], this[displayText], false);
});
}

Categories

Resources