Populating slickgrid(JS) with PHP array - javascript

I have this huge slickgrid that users can fill with data. once filled in the data is sent to the server-side with AJAX and then to the database with PHP. then I get the data out of the database and put it inside a PHP array. Now how do I populate the slickgrid with that array data. I cant seem to find the solution to this. because How to I get that php array inside the javascript slickgrid file.
javascript slickgrid for information:
<script type ='text/javascript'>
var gridArray;
var editedRows = []
function CreateColumns() {
var columns = [
{id: "hours", name: "uren", field: "hours"},
{id: "Total_inspection", name: "totaal inspectie", field: "Total_inspection", editor: Slick.Editors.Integer},
{id: "Per_hour_inspection", name: "Per uur", field: "Per_hour_inspection"},
{id: "Total_losses", name: "Totaal uitstoot", field: "Total_losses",editor: Slick.Editors.Integer},
{id: "Per_hour_losses", name: "Per uur", field: "Per_hour_losses"},
{id: "%_spil", name: "% Spil", field: "%_spil"},
{id: "%_cumul", name: "% Cumul", field: "%_cumul"},
{id: "Operator", name: "Operator", field: "Operator",editor: Slick.Editors.Text},
{id: "SKU", name: "SKU", field: "SKU",editor: Slick.Editors.Text},
{id: "End_SKU", name: "Tellerstand einde SKU", field: "End_SKU"},
{id: "Batch", name: "Batch", field: "Batch"}
];
return columns;
}
function CreateOptions() {
var options = {
editable: true,
enableCellNavigation: true,
enableColumnReorder: false,
autoEdit :false
};
return options;
}
var data = [];
function CreateData() {
for (var i = 0; i < 8; i++) {
data[i] = {
hours: 6+i+"U",
};
}
return data;
}
console.log(data)
function CreateGrid(elementId) {
if (!gridArray) { gridArray = []; }
var data = CreateData();
//editedRows.push(data)
var grid = new Slick.Grid("#" + elementId,data, CreateColumns(), CreateOptions());
gridArray[length] = grid;
//todo tets localstorage
var columnidx = data[0].Total_inspection
var columnidx2 = data[0].Total_losses
var calculation = columnidx2/columnidx
var columnidx3 = data[0].Per_hour_inspection
//push(calculation)
var columnid = data[columnidx]
//console.log(calculation,columnidx3)
grid.onCellChange.subscribe(function (e,args) {
//console.log('arguments',args.item);
editedRows.push(args.item)
console.log('arrayrows',editedRows)
});
}
console.log(editedRows)
$('#Savebtn').click(function () {
console.log(editedRows);
//var UpdatedRows = JSON.stringify(editedRows);
//console.log(UpdatedRows);
$.ajax({
type: "POST",
url: "request.php",// changed
data: {arrayOfValues: editedRows},
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
alert(data)
console.log(data)
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
PHP looks like this :
$stmt = $mysqli->prepare("SELECT * FROM kicdata");
//$stmt->bind_param('i',$id);
$stmt->execute();
$result = $stmt->get_result();
$return_data = [];
while($row = $result->fetch_assoc()){
$return_data[]= $row;
}
var_dump($return_data);
UPDATE: the use of ajax solved the part to send the server-side array to the client-side.

Related

Global Count Variable not increasing

For some reason, I cannot get my global variable counter to increase, even when it increases within the function I have the count++ occurring in. My outputted results are different between the text outputted within the function and the text outside of it. Any idea what I am doing wrong here? Shouldn't the count increase on each iteration of the survey.oncomplete function results?
Survey
.StylesManager
.applyTheme("modern");
var kn2 = "LwrHXqFRN_pszCopTKHF_Q"
var kn3 = "exroCUoYl4wVzs7pKU_49w"
var count = 0
var keyname = ("kn" + count)
var mapilink = "https://images.mapillary.com/" + (keyname) + "/thumb-1024.jpg";
var json = {
pages: [
{
name: "page1",
elements: [
{
type: "image",
name: "image",
imageLink: (mapilink),
imageHeight: 580,
imageWidth: 640
},
{
type: "html",
name: (keyname),
visible: false,
html: (keyname)
},
{
type: "rating",
name: "Walkability",
title: "How walkable does this look to you"
},
{
type: "rating",
name: "Saftey",
title: "How safe does this look to you"
},
{
type: "rating",
name: "Comfortability",
title: "How comfortable does this look to you"
}
]
}
]
}
window.survey = new Survey.Model(json);
var username = document.getElementById("user").value;
survey
.onComplete
.add(function (result) {
count ++;
var PID = document.getElementById("user").value;
var results = PID + "_" + (keyname) + ":\n" + JSON.stringify(result.data, null, 3) + (count) ;
document
.querySelector('#surveyResult')
.textContent = results;
survey.clear();
survey.render();
});
$("#surveyElement").Survey({model: survey});
Got an answer from a seperate stackexchange post - basically, I needed to wrap everything in more functions.
function outputting function text rather than expected output

Easy Autocomplete nested Json structure

I'm having a hard time to structure the list location for items array in order to access name attribute in search.js
Below is the nested JSON structure:
{
menus: [
{
name: "Summer ",
url: "/menus/2",
items: [
{
name: "man o man", //this is what I'm trying to access
url: "/menus/2/items/7"
}
]
]
}
So far I've tried in search.js:
document.addEventListener("turbolinks:load", function() {
$input = $("[data-behavior='autocomplete']")
var options = {
getValue: "name",
url: function(phrase) {
data = "/search.json?q=" + phrase;
return data;
},
categories: [
{
listLocation: "menus",
header: "--<strong>Menus</strong>--",
},
{
listLocation: "items", //this is where I'm having problem with
header: "--<strong>Items</strong>--",
}
],
list: {
onChooseEvent: function() {
var url = $input.getSelectedItemData().url
$input.val("")
Turbolinks.visit(url)
}
}
}
$input.easyAutocomplete(options)
})

ExtJs 5 Show data in grid from two stores

Is it possible to show data in table from two stores (merge them) without creating third store?
Example:
var store1 = {
data: [{
name: 'Joe'
}, {
name: 'Jane'
}, {
name: 'Kate'
}]
};
var store2 = {
data: [{
name: 'John'
}, {
name: 'Richard Roe'
}]
};
var grid = {
store: [store1, store2]
}
If both stores' models are same, why don't you merge stores' data ? then load merged data into store1. Like that: https://fiddle.sencha.com/#fiddle/tjh
var mergedData = Ext.Array.union(store1.getRange(),(store2.getRange());
store1.loadData(mergedData);
grid.setStore(store1);
// to provide unique
store1.on('datachanged', function(store) {
var checkArray = [];
Ext.each(store.getRange(), function(record) {
var userName = record.get('name');
if (checkArray.indexOf(userName) > -1) {
store.remove(record);
}
checkArray.push(userName);
});
});

Getting javascript var from database record in Smarty

I'm working on a PrestaShop page with the file extension ".tpl". I get the javascript code to auto complete like this:
var currencies = [
{ value: 'Afghan afghani', data: 'AFN' },
{ value: 'Albanian lek', data: 'ALL' },
{ value: 'Algerian dinar', data: 'DZD' },
{ value: 'European euro', data: 'EUR' },
{ value: 'Angolan kwanza', data: 'AOA' },
{ value: 'East Caribbean dollar', data: 'XCD' },
{ value: 'Vietnamese dong', data: 'VND' },
{ value: 'Yemeni rial', data: 'YER' },
{ value: 'Zambian kwacha', data: 'ZMK' },
{ value: 'Zimbabwean dollar', data: 'ZWD' },];
While I also already have a foreach like the example below:
{foreach from=$currencies item=currency}
{$currency.name}
{$currency.code}
{/foreach}
How to output currencies value with foreach? I tried this code:
var currencies = [
{foreach from=$currencies item=currency}
{ value: '{$currency.name}', data: '{$currency.code}' },
{/foreach},];
http://i.stack.imgur.com/DhYgL.jpg
You can use json_encode to output a PHP array to JavaScript
This is the JavaScript code in the TPL
var currencies = JSON.parse('{$currencies|json_encode}');
{$currencies|json_encode} will output something like this
[{ value: 'Afghan afghani', data: 'AFN' },
{ value: 'Albanian lek', data: 'ALL' },
{ value: 'Algerian dinar', data: 'DZD' }, ...]
This output will be passed to the JavaScript function JSON.parse which will transform the output string to a JavaScript object
var newArray = [];
for (var i=0; i < currencies.length; i++) {
newArray.push({value: whatever, data: whateverVar})
}
I am still not sure what you want but that is the best I can give from what I think you want.

dynamic columnDef in ng-Grid

I want to assign ng-grid columns name dynamically after value returned from database, but issue is that it get initialized before data return from ajax, and i am not able to recall gridOption so it showing balnk, so please help me that how can we construct a column name by ajax return value.
$scope.gridOptions =
{
data: 'data.Values',
columnDefs:
[
{ field: "ID", displayName: "Record Id" },
{ field: "Value", displayName: $scope.ColumnName, cellFilter: cellfilterType },
],
};
where $scope.ColumnName coming from below line...
RecordService.getRecords().then(function (data) {
$scope.ColumnName= data.something;
}
Thanks
Thanks Max for your help, I have done this with of help columnDef as below:
Step 1:
$scope.colDef = [];
Step 2:
RecordService.getRecords().then(function (data){
$scope.colDef=["ColumnName":data.something]
}
Step 3:
$scope.gridOptions = {
data: 'data.UdiValues',
columnDefs:'colDef',
filterOptions: $scope.filterOptions
};
Try to set first "default" value and after change it with promise
$scope.gridOptions =
{
data: 'data.Values',
columnDefs:
[
{
field: "ID",
displayName: "Record Id"
},
{ field: "Value",
displayName: "default",
cellFilter: cellfilterType
},
]
};
And now:
RecordService.getRecords().then(function (data) {
$scope.gridOptions.columnDefs[1].displayName = data.something;
}
The Service RecordService returns promise therefore we create promise factory like:
.factory('RecordService', ['$resource','$q', function($resource, $q) {
var data = { something: "from service" } ;
var factory = {
getRecords: function (selectedSubject) {
var deferred = $q.defer();
deferred.resolve(data);
return deferred.promise;
}
}
return factory;
}]);
Demo Fiddle
Something like this
Return json, play around, use GET mapping to strings etc?
i have done something like this :-
self.gridOptions.columnDefs = columnDefs(colDef,displayNames);
columnDef is :-
var columnDefs = function(data,cd){
var colDef= [];
var mi = null;
var colByOrder = sortedByOrder(data);
for(var i=0 ; i < colByOrder.length ; i++){
colDef.push({
width: width,
field: String(colByOrder[i][1].position),
menuItems: menuItems(this),
displayName: cd[colByOrder[i][1].position],
enableSorting: false,
type: 'string',
});
}
return colDef;
};

Categories

Resources