Dynamically set datasource for jquery datatable columns - javascript

Is there a way we can dynamically set data source of datatable columns? Like I set columns.data by hardcoding each property name like this:
$.ajax({
data: JSON.stringify(data),
url: urlGetProviderQualificationTimeData,
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (obj) {
if (obj.success) {
$('#tblProds').dataTable({
data: obj.data.ProdsDetails,
columns: [
{ "data": "PName" },
{ "data": "PTime" } //hardcoded mapping of properties
]
});
}
},
});
ProdsDetails sample array:
Array[2]
0:Object
PName:"ATT",
PTime:"6.48"
1:Object
PName:"CENTURYLINK",
PTime:"3.67"
Is there a way we can get rid of this hardcoded mapping of properties and columns?

Here is your array :
var array=[
{PName:"ATT",PTime:"6.48" },
{PName:"CENTURYLINK",PTime:"3.67"}
];
Now, You should get all the keys and build final array:
var obj=array[0];
var keys=[];
for(var k in obj)
keys.push({"data":k});
Now, keys array looks like this:
[
{"data":"PName"},
{"data":"PTime"}
]
And the last step is to assign array to columns property of DataTable:
columns:keys
Now this should look like this:
columns:[
{ "data": "PName" },
{ "data": "PTime" }
]
Hope this helps !.

I had the same problem and worked around this by creating an extra json array for the columns.data property. Is used a php function to loop through the headers and put it into a json array.

Related

Send 2 array by ajax

First I want to create a simple array with data from input
And I want to do a loop and create an array with the line from the table.
some code here.
var first_array = {
"warehouse": $("#warehouse").val(),
"pricelist": $("#pricelist").val(),
"date": $("#date").val(),
"docstatus": "DR",
"paymentterm": $("#paymentterm").val()
}
var second_array = []; //Thanks to sagar1025 help create the second array
$("#table_main tbody > tr").each(function() {
var celdas = $(this).find('td');
second_array.push({
"line": $(celdas[0]).html(),
"code": $(celdas[1]).html()
});
});
/*Here my ajax*/
$.ajax({
data: {
array1: first_array,
array2: second_array
},
url: "<?php echo base_url() ?>main/save_data",
type: 'POST',
async: false,
cache: false,
success: function(response) {
},
error: function() {
toastr.error('ERROR', '', {
progressBar: true,
closeButton: true
});
}
});
Now I need to loop the second array in my php file
Here is how I declare one var from the first_array
$docstatus = trim($this->input->post('array1[docstatus]', TRUE));
$array = $this->input->post('array2[]', TRUE);
Im using codeigniter
This is how you push or add multiple objects to an array
var second_array = [];
$("#table_main tbody > tr").each(function() {
var celdas = $(this).find('td');
second_array.push({
"line": $(celdas[0]).html(),
"code": $(celdas[1]).html()
});
});
The Ajax call should be like something like this:
$.ajax({
data: {
array1: first_array,
array2: second_array
},
url: "<?php echo base_url() ?>main/save_data",
type: 'POST',
async: false,
cache: false,
success: function(response) {
},
error: function() {
toastr.error('ERROR', '', {
progressBar: true,
closeButton: true
});
}
});
I think you are confusing between arrays and object, arrays are denoted with [] example var array=[1,2,3,4] objects are denoted with {} ex: var Obj={color:"red"}
you could send an object in your ajax call that contains both arrays or both objects depending on what you want so for instance you could do something like:
var globobj={}
var first_object= {
"warehouse": $("#warehouse").val(),
"pricelist": $("#pricelist").val(),
"date": $("#date").val(),
"docstatus": "DR",
"paymentterm": $("#paymentterm").val()
}
var second_object= {
"line": $(celdas[0]).html(),
"code": $(celdas[1]).html()
}
globobj.first_object=first_object
globobj.second_object=second_object
so now that your objects are both combined you could use the globobjto make you ajax call

Looping through an array of objects and mapping each object them to a single template object

I have a two sets of data, one formatted like so:
title: "Test Json",
showProgressBar: "top",
showQuestionNumbers: "off",
pages: [
{
questions: [
{
type: "",
name: "",
title: "",
hasOther: true,
isRequired: true,
colCount: 4,
choices: []
}
]
}
]
};
The other formatted like so:
{Answers: "“18-24”, “25-50”, “50+”",
​
Question: "How old are you?",
​
QuestionNumber: "1",
​
isRequired: "TRUE",
​
type: "radiogroup"}
This second set of data is multiple of these objects, which I am looping through using a forEach loop like so:
data.forEach((data, i)=>{
console.log(data)
// returns above object x3
})
What I want to do is use the first object and map values to the questions array using the values of the second object, so for example questions[0].type would be mapped to data.type.
I have managed to figure out mapping one object to the template doing this:
data.forEach((data, i)=>{
console.log(data)
questions[0].type = data.type
questions[0].name = data.Question
questions[0].title = data.Question
questions[0].choices = [data.Answers]
})
But this only maps the first object in the data array of objects, and I want to basically create a new template object based on the number of objects in the data array and create as many 'filled questions templates' as there is objects in data array
Any pointers and help would be lovely <3
Try this
data.forEach((data, i)=>{
console.log(data)
questions.push([{
type: data.type
name: data.Question
title: data.Question
choices: [data.Answers]
}])
})
Updated this answer with your additional question

How to map model to table when the structure is array based?

I have my data as following:
{
meta: {
format: "csv",
info: "desc",
columns: [
{
id: "Name",
type: "Text",
length: 32
},
{
id: "Text",
type: "Text",
length: 128
}]
},
rows: [
["John","xxxx"],
["Alpha","yyyy"],
["Beta","wwww"],
["Gamma","zzzz"]]
}
Now, I am struggling to map the records to a Table control as Columns and Rows. Column seems straight forward, straight map, but the rows since lacks a mapping to column I wonder what could be the simplest way.
Approach Steps:
Make a keys[] from column.id of each columns record.
Traverse the rows[]
Each loop, while keys.length create an object as {keys[j]:row[k]}
Push to an array
Recreate the original JSON but replace Rows arrays with Objects
I am really struggling to translate this into code specially at the rows[] parsing and creating Objects. Is there, I am sure there must be, an efficient way to achieve this.
Here is what you could do. using Array.map and forEach.
var input = {
meta: {
format: "csv",
info: "desc",
columns: [{
id: "Name",
type: "Text",
length: 32
}, {
id: "Text",
type: "Text",
length: 128
}]
},
rows: [
["John", "xxxx"],
["Alpha", "yyyy"],
["Beta", "wwww"],
["Gamma", "zzzz"]
]
};
var columns = input.meta.columns.map((column) => {
return column.id
});
var rows = input.rows.map((row) => {
var obj = {};
row.forEach((column, idx) => {
obj[columns[idx]] = column;
});
return obj;
});
input.rows = rows;
console.log(input);

How to pass json data to highcharts series?

I have following json array which is generated at runtime.
Hence the number of name/data pairs varies.
`var sales = { "SalesData" : [
{ "name" : "AllProducts|Canada", "data" :[44936.0,50752.0] },
{ "name" : "AllProducts|Mexico", "data" : [200679.0,226838.0] },
{ "name" : "AllProducts|USA", "data" : [288993.0,289126.0] }
]} `
I want to pass this data to series in highcharts.
This is how I am doing it currently.
series: [
{name:sales.SalesData[0].name,data:sales.SalesData[0].data},
{name:sales.SalesData[1].name,data:sales.SalesData[1].data},
{name:sales.SalesData[2].name,data:sales.SalesData[2].data}
]
But if the number of elements in array are changed then this won't work.
How do I solve this problem ? Demo code will help me.
I have refereed following questions but I was not able to solve the problem.
Dynamically adding to Highcharts
Highcharts series data array
I solved the problem
Changed json array as follows:
var sales = [
{ "name" : "AllProducts123|Canada", "data" :[44936.0,50752.0] },
{ "name" : "AllProducts|Mexico", "data" : [200679.0,226838.0] },
{ "name" : "AllProducts|USA", "data" : [288993.0,289126.0] }
]
Now pass it directly to series in highcharts.
series:sales
Done !!!!!
Instead of constructing the series array manually you could loop through the sales variable data and construct the array. So what ever the number of elements in the sales.SalesData array, all items will be there in the series array
var series = [],
salesData= sales.SalesData;
for (var i=0 i< salesData.length; i++) {
series.push({"name" : key, "data" : sales[key]})
}
This constructed series array is part of the object which you must pass as argument to highcharts method.
var chartdata = {
chart: {type: 'column'},
title: {text: 'Sales Data'},
xAxis: {
categories: ['Category 1','Category 2']
},
yAxis: {
min: 0,
title: {text: 'Sales'}
},
series : []
}
chartdata.series = series;
$('#chart').highcharts(chartdata);
where #chart is the container where you want to display the chart.
you can also refer to the fiddles which are available in their demo pages for each type of chart to know more on how to display a particular type of chart.

Required help in JSON

I have this below json data.
[{"start_date":"2014-06-27","count":"21","value":"134"},{"start_date":"2014-06-28","count":"17","value":"120"},{"start_date":"2014-06-29","count":"21","value":"138"},{"start_date":"2014-06-30","count":"9","value":"121"},{"start_date":"2014-07-01","count":"12","value":"112"},{"start_date":"2014-07-02","count":"19","value":"132"}]
I trying to plot this a line chart using highcharts.
I wanted to convert my data to something like this.
[{
name: "count",
data: [21, 17 .......]
},{
name: "value",
data: [134, 120, .......]
}]
How can I format my data like that using jquery?
I use AJAX to get that data from a database.
Any help will be very helpful.
Thanks in advance.
USE
var res= YOUR JSON DATA
var data=$.parseJSON(res);
var count= new Array();
var val=new Array();
$(data).each(function(i,u){
count.push(u.count);
val.push(u.value);
});
now you can use
[{
name: "count",
data: count
},{
name: "value",
data: val
}]
var array = [{"start_date":"2014-06-27","count":"21","value":"134"},{"start_date":"2014-06-28","count":"17","value":"120"},{"start_date":"2014-06-29","count":"21","value":"138"},{"start_date":"2014-06-30","count":"9","value":"121"},{"start_date":"2014-07-01","count":"12","value":"112"},{"start_date":"2014-07-02","count":"19","value":"132"}]
var chartOptions = [];
var countData = {name: "count", data: []};
var valueData = {name: "value", data: []};
array.forEach(function(value, index){
countData.data.push(value.count);
valueData.data.push(value.value);
});
chartOptions.push(countData);
chartOptions.push(valueData);
I would build the JSON structure required by highcharts server side, before returning it in the AJAX call. There simply adding it directly to highcharts.
This will be more efficient then letting the users browser make the formating.

Categories

Resources