Below is snippet of jquery for autocomplete:
var columns = [{
name: 'Color',
minWidth: '100px'},
{
name: 'Hex',
minWidth: '70px'},
{
name: 'Testy',
minWidth: '70px'}],
colors = [['White', '#fff','test1'], ['Black', '#000','test2'], ['Red', '#f00','test3'], ['Green', '#0f0','test4'], ['Blue', '#00f']];
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
// Set the input box's value
this.value = (ui.item ? ui.item[1] : '');
// Set the output div's value
$('#outputDiv') && $('#outputDiv').text(ui.item ? ('You have selected ' + ui.item[1]) : 'Select a color');
return false;
}
});
This will output something like this for the autocomplete:
ANd when highlighted item chosen , the second item in the array will be selected in the textbox:
Its because I've set here to choose the second item in the array via this code:ui.item[1]
But I would like to replace the jquery array with value from database:
Say I fetch data from database to be filled in the colors array:
<?php
$sql="SELECT item1,item2,item3 FROM loc_coordinate";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
$test=array();
if($result)
{
while($row=mysqli_fetch_array($result))
{
//how do I convert this 3 items into this jquery array(`colors = [['White', '#fff','test1'], ['Black', '#000','test2'], ['Red', '#f00','test3'], ['Green', '#0f0','test4'], ['Blue', '#00f']];`)
echo $row['item1'].">".$row['item2'].>".$row['item3']." \n";
}
}
?>
[1]: http://i.stack.imgur.com/G4JFs.png
[2]: http://i.stack.imgur.com/ys9Ey.png
Assuming all retreived db rows have item1,item2 and item3 values, then this should do it :
...
if($result)
{
echo 'var colors = [';
while($row=mysqli_fetch_array($result))
{
echo '[';
echo '\''.$row['item1'].'\',';
echo '\''.$row['item2'].'\',';
echo '\''.$row['item3'].'\',';
echo '],';
}
echo '];';
}
...
It will output something like :
var colors = [['row_01','row_02','row_03',],['row_01','row_02','row_03',],['row_01','row_02','row_03',],];
where row_0x is the retreived value, make this be outputted inside the <script></script> tags and when generated from server to the client side JavaScript will use it.
A cleaner solution is to use the PHP built in json_encode() function like :
if($result)
{
$output = 'var colors = ';
$all_rows = [] ;
while($row=mysqli_fetch_array($result))
{
$all_rows[]=[$row['item1'],$row['item2'],$row['item3']];
}
$output.= json_encode($all_rows).';';
echo $output;
}
This will output something like :
var colors = [["1","2","3"],["1","2","3"],["1","2","3"],["1","2","3"]];
(thanks #MikeBrant for the comment)
You may also consider a different approach by separating your html and PHP files. The PHP file will output encoded Json results wile the HTML file may use Ajax within jQuery to retrieve them. There is many good tutorials out there. Here is one of them.
This worked for me..I retrieved data from ajax in json format.
<script>
/*
* jQuery UI Multicolumn Autocomplete Widget Plugin 2.2
* Copyright (c) 2012-2015 Mark Harmon
*
* Depends:
* - jQuery UI Autocomplete widget
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-widget-header)" );
},
_renderMenu: function(ul, items) {
var self = this, thead;
if (this.options.showHeader) {
table=$('<div class="ui-widget-header" style="width:100%"></div>');
// Column headers
$.each(this.options.columns, function(index, item) {
//hide the header
//table.append('<span style="float:left;min-width:' + item.minWidth + ';"> ' + item.name + '</span>');
});
table.append('<div style="clear: both;"></div>');
ul.append(table);
}
// List items
$.each(items, function(index, item) {
self._renderItem(ul, item);
});
},
_renderItem: function(ul, item) {
var t = '',
result = '';
$.each(this.options.columns, function(index, column) {
t += '<span style="float:left;min-width:' + column.minWidth + ';">' + item[column.valueField ? column.valueField : index] + '</span>'
});
result = $('<li></li>')
.data('ui-autocomplete-item', item)
.append('<a class="mcacAnchor">' + t + '<div style="clear: both;"></div></a>')
.appendTo(ul);
return result;
}
});
//ajax starts
$("document").ready(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "GET",
dataType: "json",
url: "store2.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//$("#showPlace").html("<br />JSON: " + data );
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
// alert(data);
// console.log(data);
var columns = [{
name: 'level',
minWidth: '200px'},
{
name: 'subject',
minWidth: '70px'},
{
name: 'catid',
minWidth: '70px'}
],
colors = data;
var selectThis=$("#search").attr("class");//textbox class determines which item in array to select
var valueV=$("#search").attr("value");
$("#search").mcautocomplete({
showHeader: true,
columns: columns,
source: colors,
select: function(event, ui) {
// Set the input box's value
this.value = (ui.item ? ui.item[selectThis] : '');
//search for nearest value
// Set the output div's value
$('#outputDiv') && $('#outputDiv').text(ui.item ? ('You have selected ' + ui.item[selectThis]) : 'Select a color');
return false;
}
});
}
});
});
</script>
Related
I want displaying object data in table, which value inside name of object appear as <td>,
i have result in the network preview like this below:
I need displaying value inside A1_score and A2_score as <td>, so i tried jquery like this:
$(document).on('click', '#cektesting', function(e) {
$('.row').css({ 'visibility': 'hidden', 'display': 'none' });
$.ajax({
url: "pengguna/getCounting",
type: "GET",
dataType: "JSON",
success: function(data) {
$('.row').css({ 'visibility': 'visible', 'display': 'flex' });
$.each(data['A1_score', 'A2_score'], function(key, value) {
$('#tbodyres').append(
'<tr id="idscore"><td>' + key + '</td><td>' + value + '</td><td>' + value + '</td></tr> '
);
});
}
});
});
And last thing those data came from my Controller.php:
public function getCounting()
{
$get_row_class = $this->getdata->getAutism();
$get_row = $this->getdata->countrow();
$row_autism = $get_row_class['Autism'];
$row_normal = $get_row_class['Normal'];
$res_autism = number_format($row_autism / $get_row['jml_data_latih'], 6);
$res_normal = number_format($row_normal / $get_row['jml_data_latih'], 6);
$A_Score = $this->getdata->getA_score();
$data = [];
foreach ($A_Score as $as) {
$row['A_Y_NORMAL'] = $as['A1_YES_NORMAL'] / $row_normal;
$row['A_Y_AUTIS'] = $as['A1_YES_AUTIS'] / $row_autism;
$row['A_N_NORMAL'] = $as['A1_NO_NORMAL'] / $row_normal;
$row['A_N_AUTIS'] = $as['A1_NO_AUTIS'] / $row_autism;
$row2['A_Y_NORMAL'] = $as['A2_YES_NORMAL'] / $row_normal;
$row2['A_Y_AUTIS'] = $as['A2_YES_AUTIS'] / $row_autism;
$row2['A_N_NORMAL'] = $as['A2_NO_NORMAL'] / $row_normal;
$row2['A_N_AUTIS'] = $as['A2_NO_AUTIS'] / $row_autism;
$data['A1_score'] = $row;
$data['A2_score'] = $row2;
}
echo json_encode($data);
}
Result:
And this is what i get when i tried build jquery from jquery code above, So i get A2_score data but A1_score didn't displaying only A2_score data get looped.
You can get all keys inside your object and then use that keys to get required data from both JSON Object .
Demo Code :
//just for demo..
var data = {
"A1_score": {
"xs": 12322,
"sse": 1232
},
"A2_score": {
"xs": 1234,
"sse": 213
}
}
//get keys of one object because keys in other object are same
var keys = Object.keys(data["A1_score"])
console.log(keys)
//loop through keys
for (var i = 0; i < keys.length; i++) {
var keys_ = keys[i]
//add that inside your table
$('#tbodyres').append(
'<tr class="idscore"><td>' + keys_ + '</td><td>' + data["A1_score"][keys_] + '</td><td>' + data["A2_score"][keys_] + '</td></tr> '
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tbodyres"></table>
You can not use data['A1_score', 'A2_score'] to iterate over properties A1_score & A2_score. What you should do is iterate over either A1_score or A2_score and retrieve key. Then get values from A1_score & A1_score with data["A1_score"][key] & data["A2_score"][key].
Try like below.
$.each(data["A1_score"], function(key, value) {
$('#tbodyres').append(
'<tr id="idscore"><td>' + key + '</td><td>' + data["A1_score"][key] + '</td><td>' + data["A2_score"][key] + '</td></tr> '
);
});
I have a Morris donut/pie char that I initialize like following:
function InitializePieChart(data) {
var formedData = "";
var length = Object.keys(data).length;
$.each(data, function (index, value) {
if (index === (length - 1)) {
formedData += "{ value: '"+value.Percentage+"' , label: '" + value.SellerName + "' }";
}
else {
formedData += "{ value: '"+ value.Percentage + "' , label: '"+ value.SellerName + "' } , ";
}
});
console.log(formedData);
Morris.Donut({
element: 'pie-chart',
data: [JSON.stringify(formedData)],
backgroundColor: 'transparent',
labelColor: '#6d6d6d',
colors: [
'#012e42',
'#076178',
'#0f7c93',
'#1b99ac'
],
formatter: function (x) { return x + " %" }
});
}
As you can see here the value for the donut chart should be set to the "Percentage" property of the returned JSON, and the label should be set to the "SellerName" property...
However whatever I tried didn't work.. The returned JSON contains more properties than these two but they are irrelevant for this chart... I tried forming a JSON to inject it into the chart , but it returns as empty when the page is rendered completely..
Is there any way I can just simply inject the data into chart directly and then specify which property belongs to "label" and which belongs to "value" ?
Can someone help me out with this one?
My page has search box to filter particular column data.The text in the cell is displayed using html properties like <i> and <b>.
So it is a challenge for me to filter the text with <i> or <b>.
Here is html code for search box.
<form>
<span>EnglishStaffname</span>
<input type='text' id='EnglishStaffname_search' value=""></input>
</form>
The script to create datatable is below:
function createWidget(table) {
column_data = [
{title: "User ID", visible: false, data: "id"},
{title: "Location", visible: true, data:"location"},
title: "Details",
data: "details",
sortable: false,
render: {
display: function(data) {
json = jQuery.parseJSON(data);
s = "";
if ("subjects" in json)
{
s += "<b>subjects:</b><br />";
$.each(json["subjects"], function(key, value) {
s += " - <i>" + key + ": </i>" + value + "<br />";
});
s += "<b>hours:</b><br />";
$.each(json["hours"], function(key, value) {
s += " - <i>" + key + ": </i>" + value + "<br />";
});
}
else
{
$.each(json, function(key, value) {
s += "<b>" + key + ": </b>" + value + "<br />";
});
}
return s;
}
}
}];}
The table displays the details column like below
1st row :
subject:
-English:Meena.K
-Maths:Ramya.v
hours:
-monday:8
2nd row:
English:Kiran.K
Maths:Ramya.v
I have tried to filter details column for English using jquery something like this:
$("EnglishStaffname_search").keyup(function() {
try {
item = $(this).val();
table.column(2).search(item, true, false).draw();
} catch(e) {
}
});
But the above is searching for whole cell not for only English.I have tried regex also but not getting exact match.
Can any one suggest me to get exact match irrespective of html tags?
Web page table:
We can do it using RegEx.
Try following code-
$(document).ready(function() {
var table = $('#example').DataTable( {
responsive: true
});
$('input[type="search"]').keyup(function(){
var term = $(this).val();
if(term =='') {
regex = '';
} else{
regex = 'English:'+ term ;
}
table.search( regex, true, false ).draw();
})
});
Working jsfiddle.
How to use paging in jTable use PHP?
I have code below in employeeTable.php
<script src="jtable.2.4.0/jquery.jtable.min.js" type="text/javascript"></script>
//Get record count
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM employee;");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
Then I realize the problem is in here
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
if I change $_REQUEST["jtSorting"] = rowname, $_REQUEST["jtStartIndex"] = number, $_REQUEST["jtPageSize"] = number, it works.
But if I don't change it, it shows 'An Error Occured While Communicating to the server'.
here is the code in jquery.jtable.min.js, when there are line about jtSorting, jtStartIndex, jtPageSize
/* Adds jtSorting parameter to a URL as query string.
*************************************************************************/
_addSortingInfoToUrl: function (url) {
if (!this.options.sorting || this._lastSorting.length == 0) {
return url;
}
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
return (url + (url.indexOf('?') < 0 ? '?' : '&') + 'jtSorting=' + sorting.join(","));
},
/* Overrides _createJtParamsForLoading method to add sorging parameters to jtParams object.
*************************************************************************/
_createJtParamsForLoading: function () {
var jtParams = base._createJtParamsForLoading.apply(this, arguments);
if (this.options.sorting && this._lastSorting.length) {
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
jtParams.jtSorting = sorting.join(",");
}
return jtParams;
}
});
})(jQuery);
Can anybody please help me understand?
I think you should go through this once.
Listaction jtable for Pagination and sorting table
It would require jQuery.Deferred to return data.
Handle it as
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Employee_Controller/EmployeeList_method?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'POST',
dataType: 'json',
data: postData,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
Manually post values for it. I hope this maybe helpful.
the options will be received in $_GET object
like:
$jtStartIndex=$_GET['jtStartIndex'];
$jtPageSize=$_GET['jtPageSize'];
$jtSorting=$_GET['jtSorting'];
example:
$query="select * FROM products ORDER BY $jtSorting LIMIT $jtStartIndex, $jtPageSize;";
and in jtable settings:
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'name ASC' ,
actions: {
listAction: 'data/products.php'//Set default sorting
},
...
I have a form that submits a new entry via ajax and returns the entry data. I'm trying to get the returned data to be automatically selected in the Select2 field. I can get the id entered as the input value, but I'm not sure how to get the text to be displayed in the span.
Here's the JS I have so far:
function clientFormatResult(client){
var markup = client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
return markup;
}
function clientFormatSelection(client) {
$('#client-input').empty();
$('#client-input').append('<input type="hidden" name="client" value="' + client.id + '" />');
return client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
}
$('#client-selection').select2({
placeholder: 'Select a client',
allowClear: true,
minimumInputLength: 1,
ajax: {
type: 'POST',
url: 'clients/get_client_list',
dataType: 'json',
data: function (term) {
return {filter: term};
},
results: function (data) {
return {results: data};
}
},
formatResult: clientFormatResult,
formatSelection: clientFormatSelection,
dropdownCssClass: 'bigdrop',
initSelection: function (element, callback) {
var id = element.val();
if(id != '') {
$.ajax('clients/get_client_list/'+id).done(function(data) {
data = $.parseJSON(data);
callback(data);
});
}
}
});
$('#add-client-form').submit(function(e) {
e.preventDefault();
var form = $(this),
url = form.attr('action'),
data = form.serialize();
$.post(url, data, function(data, status, xhr) {
$('.form-response').fadeOut(400);
if(status == 'success') {
$('#add-client-modal').modal('hide');
data = $.parseJSON(data);
$('#client-selection').select2('val', data.client_id);
} else {
$('#add-client-failure').fadeIn(400);
}
});
});
As you can see, the text displayed is meant to be like "John Smith (smithj)".
I sorted it out, it was an issue with the data I was returning. Select2 was expecting an id variable, but I was returning it as client_id.