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>
Related
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
I am working on google charts at the minute and I have got a basic one setup.
What it does at present is connects to a DB and returns a dataset based on 1 query. I am wondering is, if I want to draw more charts with different queries to the database how do I do this? Or what is the best practice?
For instance, there is already one connection with one query, how can I add another query, and then draw the charts based on what is returned?
I understand that might be a broad question, but maybe someone could show me how I would return a different query/dataset from the DB?
This is my code:
$(document).ready(function(){
console.log("hello world")
//alert("result")
$.ajax({
url:"data.php",
dataType : "json",
success : function(result) {
google.charts.load('current', {
'packages':['corechart','bar']
});
google.charts.setOnLoadCallback(function() {
console.log(result[0]["name"])
drawChart(result);
});
}
});
//add a 2nd call - will need a 2nd draw charts to draw the different dataset assuming it will be different
// - will need a 2nd data.php as the query will be different on the dataset
$.ajax({
url:"data.php",
dataType : "json",
success : function(result2) {
google.charts.load('current', {
'packages':['corechart','bar']
});
google.charts.setOnLoadCallback(function() {
console.log(result2[0]["name"])
drawChart(result2);
});
}
});
function drawChart(result) {
var data = new google.visualization.DataTable();
data.addColumn('string','Name');
data.addColumn('number','Quantity');
var dataArray=[];
$.each(result, function(i, obj) {
dataArray.push([ obj.name, parseInt(obj.quantity) ]);
});
data.addRows(dataArray);
var piechart_options = {
title : 'Pie Chart: How Much Products Sold By Last Night',
width : 400,
height : 300
}
var piechart = new google.visualization.PieChart(document
.getElementById('piechart_div'));
piechart.draw(data, piechart_options)
var columnchart_options = {
title : 'Bar Chart: How Much Products Sold By Last Night',
width : 400,
height : 300,
legend : 'none'
}
//var barchart = new google.visualization.BarChart(document
// .getElementById('barchart_div'));
//barchart.draw(data, barchart_options)
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(columnchart_options));
} //have added this column chart but need to wrok out if it is best practice????
});
I am getting an object back from my DB query, but I want to know how to return more/different datasets from the same DB connection? For example what if I wanted to draw another chart with the dataset returned from this query select * from product where name="Product1" OR name="Product2";
0: Object { id: "1", name: "Product1", quantity: "2" }
1: Object { id: "2", name: "Product2", quantity: "3" }
2: Object { id: "3", name: "Product3", quantity: "4" }
3: Object { id: "4", name: "Product4", quantity: "2" }
4: Object { id: "5", name: "Product5", quantity: "6" }
5: Object { id: "6", name: "Product6", quantity: "11" }
For what it is worth my php code is as follows:
data.php
<?php
require_once 'database.php';
$stmt = $conn->prepare('select * from product');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
echo json_encode($results);
?>
database.php
<?php
$conn = new PDO('mysql:host=192.168.99.100;dbname=demo','root', 'root');
?>
note: this might be of interest
google charts only needs to be loaded once per page load,
not every time you need to draw a chart
also, google.charts.load can be used in place of --> $(document).ready
it will wait for the page to load before executing the callback / promise
recommend setup similar to following snippet...
google.charts.load('current', {
packages: ['corechart', 'bar']
}).then(function () {
$.ajax({
url: 'data.php',
dataType: 'json'
}).done(drawChart1);
$.ajax({
url: 'data.php',
dataType: 'json'
}).done(drawChart2);
});
function drawChart1(result) {
...
}
function drawChart2(result) {
...
}
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.
I am using the select2 for on of my search boxes. I'm getting the results from my URL but I'm not able to select an option from it. I want to use the 'product.productName' as the text to be shown after selection. Is there anything that I have missed out or any mistake that I have made. I have included select2.css and select2.min.js,jquery.js
function dataFormatResult(product) {
var markup = "<table class='product-result'><tr>";
markup += "<td class='product-info'><div class='product-title'>" + product.productName + "</div>";
if (product.manufacturer !== undefined) {
markup += "<div class='product-synopsis'>" + product.manufacturer + "</div>";
}
else if (product.productOptions !== undefined) {
markup += "<div class='product-synopsis'>" + product.productOptions + "</div>";
}
markup += "</td></tr></table>";
return markup;
}
function dataFormatSelection(product) {
return product.productName;
}
$(document).ready(function() {
$("#e7").select2({
placeholder: "Search for a product",
minimumInputLength: 2,
ajax: {
url: myURL,
dataType: 'json',
data: function(term,page) {
return {
productname: term
};
},
results: function(data,page) {
return {results: data.result_object};
}
},
formatResult: dataFormatResult,
formatSelection: dataFormatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
This is my resut_object
"result_object":[{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"},{"productName":"samsung salaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Graphite;32GB"},{"productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;16GB"}]
You are missing id attribute for result data. if it has not, it makes option "unselectable".
Example:
$('#e7').select2({
id: function(e) { return e.productName; },
});
Since I was using AJAX, what worked for me was returning something as the ID on processResults:
$(field).select2({
ajax: {
// [..] ajax params here
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
// proccessResults NEEDS the attribute id here
id: item.code,
// [...] other attributes here
foo: item.bar,
}
})
}
},
},
});
The id param can be a string related to the object property name, and must be in the root of the object. Text inside data object.
var fruits = [{code: 222, fruit: 'grape', color:'purple', price: 2.2},
{code: 234,fruit: 'banana', color:'yellow', price: 1.9} ];
$(yourfield).select2(
{
id: 'code',
data: { results: fruits, text: 'fruit' }
}
);
I have faced the same issue,other solution for this issue is:-
In your response object(In above response Product details object) must have an "id" as key and value for that.
Example:- Your above given response object must be like this
{"id":"1","productName":"samsung galaxy s3","manufacturer":"Samsung","productOptions":"Color;Memory","productOptiondesc":"Silver;32GB"}
SO you don't need this
id: function(object){return object.key;}
I am trying to use http://podio.github.com/jquery-mentions-input/ to add the #mentions functionality to my website. I'm trying ajax to get a JSON response from a .php file that queries the database onkeyup, but I don't know where in the code to put the ajax call.
I know I am asking for people to basically do the work for me, but I am dying here, I have been trying this for about 2-3 days now
here are two JavaScript functions from the plugin, I just an example ajax function that would link to my PHP script that searches for users %LIKE% the query.
BASIC EXAMPLE FROM PLUGIN
$(function () {
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
var data = [
{ id:1, name:'Kenneth Auchenberg', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:2, name:'Jon Froda', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:3, name:'Anders Pollas', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:4, name:'Kasper Hulthin', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:5, name:'Andreas Haugstrup', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:6, name:'Pete Lacey', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:7, name:'kenneth#auchenberg.dk', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:8, name:'Pete Awesome Lacey', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' },
{ id:9, name:'Kenneth Hulthin', 'avatar':'http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif', 'type':'contact' }
];
data = _.filter(data, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, data);
}
});
$('.get-syntax-text').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
alert(text);
});
});
$('.get-mentions').click(function() {
$('textarea.mention').mentionsInput('getMentions', function(data) {
alert(JSON.stringify(data));
});
}) ;
});
AJAX EXAMPLE(i don't know how to get the JSON from a .php file)
$(function () {
$('textarea.mention-example2').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('assets/data.json', function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
});
i figured it out, i just added a variable query with the value of query, and sent it to my script, which then searches the db and sends back the result
$('textarea.mention-example2').mentionsInput({
onDataRequest:function (mode, query, callback) {
var myquery = 'query='+query;
$.getJSON('data.php', myquery, function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
I have read up a bit on the plugin on the Gitpage, I am not sure on what you have, but this is what you need to make it work:
jQuery js file, and the plugin script.
JS Code:
$(function () {
$('textarea.mention-example2').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('assets/data.json', function(responseData) {
responseData = _.filter(responseData, function(item) {
return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 }); callback.call(this, responseData);
});
}
});
});
JSON file in the folder assets with the filename data.json 'assets/data.json':
[
{
"id": 1,
"name": "Kenneth Auchenberg",
"avatar": "http://cdn0.4dots.com/i/customavatars/avatar7112_1.gif",
"type": "contact"
}
]
Now all you need is a textarea with the class mention-example2. You might need some css files include aswell. But try this out and come back with feedback.
this is how i did in codeigniter
create a function that will get the data for me
function getDataMention(mode, query, callback){
var path = '<?=site_url()?>users/get_user_search_string/'+query;
$.ajax({
url: path,
dataType: 'json', // Choosing a JSON datatype
}).done(function(retdata) {
var data = retdata;
data = _.filter(data, function(item) {return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, data);
});
}//end getDataMention();
then call the library on document ready
$('textarea.mention').mentionsInput({
onDataRequest:getDataMention,
minChars: 1,
templates:{
wrapper: _.template('<div class="mentions-input-box"></div>'),
autocompleteList: _.template('<div class="mentions-autocomplete-list"></div>'),
autocompleteListItem: _.template('<li data-ref-id="<%= id %>" data-ref-type="<%= type %>" data-display="<%= display %>"><%= content %></li>'),
autocompleteListItemAvatar : _.template('<img src="<%= avatar %>" />'),
autocompleteListItemIcon: _.template('<div class="icon <%= icon %>"></div>'),
mentionsOverlay: _.template('<div class="mentions"><div></div></div>'),
mentionItemSyntax: _.template('#[<%= value %>](<%= type %>:<%= id %>)'),
mentionItemHighlight: _.template('<a target="__blank" class="mlink" href="<?=site_url()?>users/profile/profile_id=<%= id %>"><%= value %></a>')
}
});