I have some problems when I try to export my data as excel using the datatables button.
When my data type is a number and starts from 0, this value will disappear.
and also they automatically provide (.) dot as a delimiter. can someone help me to fix this??
my data
when export as excel
I want my data like this. without (point) and number 0 is not lost when the number 0 is at the beginning
this my script
$('#submitdata').on('click',function(){
var vbasedon = $("#selbased").val();
var mulai = $("#start_date").val();
var selesai = $("#end_date").val();
var vtipe = '';
if(vbasedon=='apartemen' || vbasedon=='rusunawa'){
var vtipe=$(".tipedt").val();
} else {
vtipe='';
}
$.ajax({
url: "<?= base_url('index.php/')?>",
data: {vbasedon:vbasedon,mulai:mulai,selesai:selesai,vtipe:vtipe},
cache: false,
type: "POST",
dataType:"JSON",
success: function(msg){
initEffortStandardTable(msg);
}
});
});
function initEffortStandardTable(dataObject) {
var effortStandardTable = $('.laporan').DataTable();
var columns = [];
Object.keys(dataObject[0]).forEach(column=> {
if (column === 'ctotalPerYear'
|| column === 'ftotalPerYear'
|| column === 'CPUETotalPerYear') return;
columns.push({
data: column,
title : column.toString().toUpperCase().replace('_', ' '),
footer: column
});
});
effortStandardTable.destroy();
$('#laporan').empty();
var html = `<table class="table table-striped table-bordered table-hover laporan" ></table>`;
$('#laporan').append(html);
effortStandardTable = $('.laporan').DataTable({
data: dataObject,
columns : columns,
"bDestroy": true,
responsive: true,
dom: '<"html5buttons"B>lTfgitp',
buttons: [
{ extend: 'copy'},
{extend: 'excel', title: 'Laporan'},
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'A4'
}]
});
}
I have found the answer to my question.
I just need to manipulate data by adding unicode '\u200C'.
so my code will be like this
columns.push({
data: column,
title : column.toString().toUpperCase().replace('_', ' '),
footer: column,
render:
data=>{data=> column == 'NIM' ? '\u200C'+data : data
});
and this is my results.
A number that contains more than 15 digits in Excel, it changes any digits past the fifteenth place to zeros. You can cast the column values to string on export.
//Use customizeData
exportOptions: {
//--
},
customizeData: function (data) {
var ind = data.header.indexOf("ColumnName"); // This code is to find the column name's index which you want to cast.
for (var i = 0; i < data.body.length; i++) {
data.body[i][ind] = '\u200C' + data.body[i][ind]; //will cast the number to string.
}
}
Error_Image below:
https://i.stack.imgur.com/A39hf.png
Related
In my function I search with jquery all items of a owl carousel and take from the id only the available numbers. Because I only need the ID numbers of the items. I send the ID numbers via ajax to my php controller for further processing.
var slideArray = $('#categoryInterestCarousel_' + categoryIdOld).find('.interestOwl');
//Step 1: initialize the array
var previewIds = [];
//Step 2: Search for all IDs and add only the id to the array
$(function() {
$(slideArray).each(function(index) {
previewIds[index] = $(this).attr('id').replace(/\D/g, '');
});
});
As output I get the following array:
array:3 [
0 => "183"
1 => "198"
2 => "201"
]
I need the array without quotation marks, which it looks like:
array:3 [
0 => 183
1 => 198
2 => 201
]
Send data via ajax:
$.ajax({
type: 'GET',
url: '/categorie/owl/' + categoryIdOld,
data: {
previewIds: previewIds
},
success: function(data) {
//add some data to view
},
error: function(xhqr, staus, message) {
var response = JSON.parse(xhqr.responseText);
var errors = response.errors;
for (var error_key in errors) {
var error = errors[error_key];
_toastr_new(error, "top-full-width", "error", false, '.toastr-notify', 0);
}
}
});
get data on Controller:
public function ajaxOwlItems(Request $request, $id) {
$preview_id = $request->previewIds;
dd($request->previewIds);
}
Where's my mistake? How can I remove the quotation marks?
Like this - you need to cast the string to number - I use +
I took the liberty to streamline the code too - for example no need to use $(slideArray) since it is already a jQuery collection.
let categoryIdOld =3;
const previewIds = $('#categoryInterestCarousel_' + categoryIdOld)
.find('.interestOwl')
.map(function() { return +this.id.replace(/\D/g, ''); })
.get();
console.log(previewIds);
console.log(JSON.stringify(previewIds)); // still numeric
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="categoryInterestCarousel_3">
<span class="interestOwl" id="x183"></span>
<span class="somethingElse" id="x999"></span>
<span class="interestOwl" id="x198"></span>
<span class="interestOwl" id="x201"></span>
</div>
Just add parseInt() around the value:
$(function() {
$(slideArray).each(function(index) {
previewIds[index] = parseInt($(this).attr('id').replace(/\D/g, ''), 10);
});
});
I'm trying to use DataTable to show all fields of my JSON, but I'm not understand how to use it.
I just need how to populate dataset correctly to read data.
<script>
<?php
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
var max=json.items.length;
for (i=0;i<max;i++){
var el=json.items[i];
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
})
<?php }?>
var dataSet = [
/*HOW?*/
];
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
</script>
<table id="example" class="table table-responsive table-hover table-dynamic filter-head"></table>
First, two comments about your code.
As #Patrick Q stated, your PHP tags are useless: you are writing Javascript, PHP is another things that has nothing to do with your code, so remove <?php and <?php }?>
Then, i can't understand this code:
for (i=0;i<max;i++){
var el=json.items[i];
}
This for is completely useless. you cycle through every element in json.items without performing any operation. At the end you just store the last json.items in the el (without even using el in your code).
By the way, your main question:
As said in the official documentation, your dataSet must contain an array for every row of your table in the format:
var dataSet = [
["john","italy","home","john",15,20],
["john","italy","home","john",15,20]
]
This example will create two identical rows with random data inside.
Assuming every item in your json has name country home user likes contribs fields you will need something like that:
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].name,json.items[i].country, json.items[i].home, json.items[i].user, json.items[i].likes, json.items[i].contribs]
dataSet[i] = el;
}
Sorry guys. I've truncated my prev code. Now the building of data array works like a charm. I've just a doubt about a console error:
"jquery.dataTables.min.js:5 Uncaught TypeError: Cannot read property 'aDataSort' of undefined"
I can't show my rows. According with your opinion, what's the problem?
Thank you!
<script>
< ?php
if (isset($_GET) && isset($_GET['id'])){
?>
$( document ).ready(function() {
carica_ingrediente('<?php echo $_GET['id'];?>');
});
<?php }else {?>
$('#query').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER) {
$('#cerca').click();
}
});
$(document).ready(function() {
var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
.done(function(json) {
if (json.res==0){
alert( "Inserisci una parola per iniziare la ricerca " );
return;
}
var dataSet = [];
for (i=0;i<json.items.length;i++){
var el = [json.items[i].nome,json.items[i].completo, json.items[i].home, json.items[i].utente, json.items[i].likes, json.items[i].countingredienti];
dataSet[i] = el;
console.log(el);
}
$(".risultato_ricerca").click(function() {
carica_ingrediente($(this).attr('data-id'));
});
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet,
columns: [
{ title: "Nome" },
{ title: "Stato" },
{ title: "Home" },
{ title: "Utente" },
{ title: "Mi piace" },
{ title: "Contributi" }
]
} );
} );
})
.fail(function() {
alert( "error" );
});
});
<?php }?>
</script>
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_tags').on("change", function(e) {
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag " + e.added.id + "?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.
I'm a newbie php/js/mysql programmer.
I'm trying to create a pie chart in highcharts using jquery, where the data is discovered dynamically via ajax from echo json_encode in php (includes a select query from mysql).
Two problems:
1) The pie chart has these trailing "Slice: 0 %" flares everywhere. Don't know where these are coming from, what it means, nor how to fix it.
2) Json is new to me. The json data feed appears to be getting through (firebug sees it), but the format looks like this. I'm trying to boil it down to name and percent number only. Like this ['Pages', 45.0] but not sure how. Is this done in the json/php or should it be done in the sql query itself?
[{"contenttype":"BLOGPOST","count(*)":"2076"},{"contenttype":"COMMENT","count(*)":"2054"},{"contenttype":"MAIL","count(*)":"29448"},{"contenttype":"PAGE","count(*)":"33819"}]
Any help much appreciated
The highcharts js file is here:
//Define the chart variable globally,
var chart;
//Request data from the server, add it to the graph and set a timeout to request again
function requestData() {
$.ajax({
url: 'hc1.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
$(document).ready(function(){
//Create the test chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'mycontainer2',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
events: {load: requestData}
},
title: {text: 'Content Types in Wiki'},
tooltip: {formatter: function() {return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
//color: Highcharts.theme.textColor || '#000000',
//connectorColor: Highcharts.theme.textColor || '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Content',
data: []
}]
});
The php file is here:
<?php
// Set the JSON header
header("Content-type: text/json");
// Connect to db
include('dbconnect.php');
// Count version 1 of content types of interest
$query = ("select contenttype, count(*)
from CONTENT
where version='1' and contenttype='page' or contenttype='comment' or contenttype='blogpost' or contenttype='mail' or contenttype='drafts'
group by CONTENT.contenttype;");
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
// create a php array and echo it as json
//$row = mysql_fetch_assoc($result);
//echo json_encode($row);
$results = array(); while ( $row = mysql_fetch_assoc( $result )) { $results[] = $row; }
echo json_encode($results);
?>
First problem, how do you get your data into a format that highcharts is going to accept (namely arrays of arrays, [[name,percent],[nextname,percent],etc])? I would handle this in your PHP:
<snip>
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$total = 0;
$results = array();
while ( $row = mysql_fetch_assoc( $result )) {
$results[$row["contenttype"] = $row["count()"];
$total += $row["count()"];
}
$forHigh = array();
foreach ($results as $k => $v) {
$forHigh[]=array($k,($v/$total) * 100); // get percent and push onto array
}
echo json_encode($forHigh); // this should be an array of array
Now that our JSON returned structure is ready for HighCharts, we just need to call the plot creation once after our JSON call to create the plot. I would do it in the success callback of the $.ajax call.
$.ajax({
url: 'hc1.php',
success: function(jsonData) {
chart = new Highcharts.Chart({
<snip>
series: [{
type: 'pie',
name: 'Content',
data: jsonData
}]
<snip>
},
cache: false
});