I'm using https://www.devbridge.com/sourcery/components/jquery-autocomplete/
I want to get results grouped by category when using ajax.
this only work when using: lookup: teams like this:
var teams = [
{ value: 'Chicago Blackhawks', data: { category: 'NHL', link: 'website.com' } },
{ value: 'Chicago Bulls', data: { category: 'NBA', link: 'site.com' } }
];
but i want to use it with "serviceUrl:" (ajax).
This is my PHP output:
$suggestions = "[{ value: 'Chicago Blackhawks', data: { category: 'NHL', link: 'website.com' } },
{ value: 'Chicago Bulls', data: { category: 'NBA', link: 'site.com' } }
]";
return json_encode($suggestions);
but it troughs and javascript error: "TypeError: e is undefined"
Thanks.
Related
I am using jQuery data tables and fill the data via ajax as json:
https://datatables.net/examples/ajax/simple.html
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
}
});
The response of getData.php will be like this:
$myArray['data'][] = array(
"Value 1",
"Value 2",
"Value 3"
}
echo json_encode($myArray);
This works fine:
But how can I define that - for example - value 2 should be text-align right in my table?
Try this
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
},
'columnDefs': [{
"targets": 1,
"className": "text-right",
}]
});
You can use render method available in Datatables.
{
data: 'value 2 column',
render: function ( data, type, row ) {
return `<span style="text-align:right">${data}</span>`;
}
}
You can also use css if all column values are right aligned.
Within my Laravel project I am implementing the chart.js library trying to visualize a bar graph.
Which should show all work orders in finished status that were assigned to users with the operator role.
When you want to graph, simply no data is displayed, it is an empty graph.
This is my ReportController controller with this method public function getChart () I do my query
public function getChart(Request $request)
{
$_orders = DB::table('users')
->join('orders','orders.user_id','=','users.id')
->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
->select('users.id','users.name', DB::raw('COUNT(orders.id) as orders_by_user'), 'model_has_roles.role_id as rol')
->where('model_has_roles.role_id', '2');
$_orders->groupBy('orders.user_id', 'users.id', 'users.name', 'model_has_roles.role_id');
$orders=$_orders->get();
return ['orders' => $orders];
}
This is the result of my query: as it is observed I have what I need username and the number of orders completed per user.
{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}
Here is an important question: is the JSON structure returned by my query correct? With this result can I graph?
This is my report.js file for the graph:
With the renderChart() method:
I make the graph, through the data obtained in my ajax call.
With the getChartData () method:
I make my ajax call.
function renderChart(data, labels) {
var ctx = document.getElementById("orders").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'ordenes',
data: data,
borderColor: 'rgba(75, 192, 192, 1)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
borderWidth: 1,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
title: {
display: true,
text: "Ordenes en estado terminado"
},
}
});
}
function getChartData() {
$.ajax({
url: '/admin/reports/getChart',
type: 'GET',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'json',
success: function (data) {
// console.log(data);
var data = [];
var labels = [];
for (var i in data) {
data.push(data[i].orders_by_user);
labels.push(data[i].name);
}
renderChart(data, labels);
},
error: function (data) {
console.log(data);
}
});
}
$("#renderBtn").click(
function () {
getChartData();
}
);
In other words I am looking to optimize my query using eloquent, so that it returns a valid JSON response for chart.js.
Dump those data obtained through an ajax call and draw
Could you help me find and solve my error?
UPDATED 1
Just in case if any error arises change my for: for (var i in data) to this: for (var i in response)
So it looks like this:
for (var i in response) {
data.push(response[i].orders_by_user);
labels.push(response[i].name);
}
I think that I am not accessing correctly the data that I get from my query to later graph.
In the console I see the following information:
{orders: Array(3)}
orders: Array(3)
0: {id: 4, name: "Luis", orders_by_user: 2, rol: 2}
1: {id: 6, name: "Jose", orders_by_user: 1, rol: 2}
2: {id: 7, name: "Miguel", orders_by_user: 1, rol: 2}
length: 3
__proto__: Array(0)
__proto__: Object
Orders is my array, so how can I just access orders_by_user and name and correctly pass it to my data.push and labels.push
try something like this but it doesn't work:
data.push(response[i].orders.orders_by_user);
labels.push(response[i].orders.name);
I have a kendo DropDownList template in which I want to select a specific record by id without using index.
What I want is to select a record with CustomerID
following is my code
$(document).ready(function() {
$("#shopSupplier").kendoDropDownList({
change:shopSupplierSelect,
dataTextField: "ContactName",
dataValueField: "CustomerID",
valueTemplate: 'template',
template: 'template',
dataSource: {
transport: {
read: {
dataType: "json",
cache:false,
url: "<?=base_url()?>/controller/method",
}
}
}
//,index:1 /// **I dont want this**
});
var dropdownlist = $("#shopSupplier").data("kendoDropDownList");
});
If you want to use the id instead of the index you should use:
var dropdownlist = $("#shopSupplier").data("kendoDropDownList");
dropdownlist.select(function(dataItem) {
return dataItem.CustomerID === 4; // Replace it by the ID of the customer
});
making it generic:
var dropdownlist = $("#shopSupplier").data("kendoDropDownList");
function selectByID(id) {
dropdownlist.select(function(dataItem) {
return dataItem.CustomerID === id;
});
}
selectByID(2);
Working example:
$(document).ready(function() {
function shopSupplierSelect() {
alert ("select");
}
$("#shopSupplier").kendoDropDownList({
change:shopSupplierSelect,
dataTextField: "ContactName",
dataValueField: "CustomerID",
valueTemplate: kendo.template($("#template").html()),
template: kendo.template($("#template").html()),
dataSource: {
transport: {
read: function(op) {
var data = [
{ CustomerID: 1, ContactName: "John" },
{ CustomerID: 3, ContactName: "Jack" },
{ CustomerID: 5, ContactName: "Joseph" },
{ CustomerID: 6, ContactName: "Jill" },
{ CustomerID: 2, ContactName: "Jeff" },
{ CustomerID: 4, ContactName: "Jane" }
];
op.success(data);
}
}
}
//,index:1 /// **I dont want this**
});
var dropdownlist = $("#shopSupplier").data("kendoDropDownList");
function selectByID(id) {
dropdownlist.select(function(dataItem) {
return dataItem.CustomerID === id;
});
}
selectByID(2);
});
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2015.1.429/styles/kendo.default.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://cdn.kendostatic.com/2015.1.429/js/kendo.all.min.js"></script>
<input id="shopSupplier" />
<script id="template" type="text/kendo-templ">
<div><b>#= CustomerID # </b> #: ContactName #</div>
</script>
Kendo UI DropDownList has select method to select specific item. Take a look at this link here
<input id="dropdownlist" />
<script>
$("#dropdownlist").kendoDropDownList({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id"
});
var dropdownlist = $("#dropdownlist").data("kendoDropDownList");
// selects item if its text is equal to "test" using predicate function
dropdownlist.select(function(dataItem) {
return dataItem.CustomerID == 12345;
});
</script>
Having fun playing around with jtable,but got myself stuck in a bit of a rut.
I'm having a problem accessing data from a POST request. I'm trying to pass a variable from a field value in the table so I can make a custom SQL query.
My mainpage.php:
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Trip data';
ajaxSettings: {
type: 'POST'
},
actions: {
listAction: 'tableactions.php?action=list',
updateAction: 'tableactions.php?action=update',
deleteAction: 'tableactions.php?action=delete'
},
fields: {
user_id: {
key: true,
edit: false,
list: false
},
name: {
title: 'Name',
edit: false,
list: false
},
trip_id: {
title: 'Trip ID',
list: false,
edit: false
},
trip_name: {
title: 'Trip Name',
width: '50%'
},
time: {
title: 'Start time',
width: '25%',
edit: false
},
date: {
title: 'Start date',
width: '25%',
edit: false
}
}
});
//Load person list from server
$('#PeopleTableContainer').jtable('load');
});
I added the AJAX property to ensure it's set to post. Here's a portion of tableactions.php:
if($_GET["action"] == "list")
{
//Get user ID
$user_id = $_POST['user_id'];
//SQL query
$result = mysql_query("select * from userdata WHERE user_id=$user_id group by trip_id");
//Add selected records into an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
I've tried changing $user_id to a correct value manually and the table works and displays the correct information. Really racking my brains to try and solve this.
Have I missed something obvious? Why can't I get a value from $_POST?
Any help would be greatly appreciated!
I fixed this by cleaning my code and adding this into the table properties:
ajaxSettings: {
type: 'POST',
data: {'UserId': '<?php echo $userid;?>'},
url: './tableactions.php'
},
Works fine now.
I am facing a problem in the code below. I am trying to catch the MySql query result set in a variable and use the same variable in the below mentioned JQuery code. Now the problem is that my array has more than 150 items. Can anyone please guide me how to catch the MySql Array in a variable and use the result set in below mentioned JQuery code.
valueMatches : function(category, searchTerm, callback) {
switch (category) {
case 'account':
callback([
{ value: '1-amanda', label: 'Amanda' },
{ value: '2-aron', label: 'Aron' },
{ value: '3-eric', label: 'Eric' },
{ value: '4-jeremy', label: 'Jeremy' },
{ value: '5-samuel', label: 'Samuel' },
{ value: '6-scott', label: 'Scott' }
]);
break;
case 'filter':
callback(['published', 'unpublished', 'draft']);
break;
case 'access':
callback(['public', 'private', 'protected']);
break;
you could do something like this:
<script>
var passedArray = <?echo json_encode($yourArray);?>;
</script>
this will result in a javascript array that is stored in the passedArray variable and that will be accessible in your js