Accessing object data in datatables through get function - javascript

I am trying to create an object that I can modify as per
Datatables - Data
I use the following code to create my object
function projectData(projid,projdesc,descdet){
this._projid = 'HTML1'
this._projdesc = 'HTML2'
for(var i=0;i<=7;i++){
this['_day'+i] = 'HTML3';
}
this.projid = function(){
return this._projid
}
this.projdesc = function(){
return this._projdesc
}
this.day0 = function(){ // More of these for day (0-7)
return this._day0
}
}
Then I use the following table initialization. (prjData is an array of New projectData objects)
var table = $('#table-ProjectHours').DataTable({
data: prjData,
"columns": [
{ data: 'projid',"visible": true},
{ data: 'projdesc',"width": "45%" },
{ data: 'day0',"orderDataType": "dom-text-numeric" },
{ data: 'day1',"orderDataType": "dom-text-numeric" },
{ data: 'day2',"orderDataType": "dom-text-numeric" },
{ data: 'day3',"orderDataType": "dom-text-numeric" },
{ data: 'day4',"orderDataType": "dom-text-numeric" },
{ data: 'day5',"orderDataType": "dom-text-numeric" },
{ data: 'day6',"orderDataType": "dom-text-numeric" },
{ data: 'day7',"orderDataType": "dom-text-numeric" }
]
});
I access my table through
var dto = $('#table-ProjectHours').DataTable().data();
I get my objects as seen here:
What I do not understand is why when I attempt to do dto[0].day0 I do not get _day0 --- I just get the function string.
I can access the data through _day0 but it seems wrong...

Try rows().data() https://datatables.net/reference/api/rows().data()
e.g.
var table = $('#example').DataTable();
var data = table
.rows()
.data();
alert( 'The table has '+data.length+' records' );

In order to set data in jquery-datatables you must use .row(index).data(obj) or .cell(selector).data(obj).
You can also use row(index).day0() and if you write a set portion of your method you can set the data like row(index).day0(thing_to_set) You must call row(index).invalidate after changing the data for it to appear correctly.
In this particular situation, .day0 must be called as .day0() since it is a method.

Related

How to split array and only save specific value into database? Laravel with Ajax

I have a question. I need to save array into database but I need to divide it first and only save specific value. I am using Ajax and pass the data to controller.
ps: the array set can be more than 1 so each set need to split and store based on columns inside DB.
my javascript that contain Ajax:
Hotspot.prototype.saveData = function (data) {
if (!data.length) {
return;
}
// Get previous data
var raw_data = localStorage.getItem(this.config.LS_Variable);
var hotspots = [];
if (raw_data) {
hotspots = JSON.parse(raw_data);
}
// Append to previous data
$.each(data, function (index, node) {
hotspots.push(node);
});
console.log(hotspots);
// var field=JSON.stringify(hotspots).split(',');
this.data=data;
$.ajax({
type:"POST",
url:"/store",
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
Title: JSON.stringify(hotspots),
Message: JSON.stringify(hotspots),
x: JSON.stringify(hotspots),
y: JSON.stringify(hotspots),
},
success: function(data){
console.log(data,d);
},
error: function(data)
{
console.log(data);
},
});
localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots));
this.element.trigger('afterSave.hotspot', [null, hotspots]);
};
Controller:
public function storePin(Request $request)
{
request()->validate([
'Title' => 'required',
'Message' => 'required',
'x'=> 'required',
'y'=>'required',
]);
dd($request);
if ($request->all())
{
$pin = new Pin();
$pin->Title=json_encode($request->input('Title'));
$pin->Message= json_encode($request->input('Message'));
$pin->x = json_encode($request->input('x'));
$pin->y =json_encode($request->input('y'));
$pin->save();
// return response()->json_encode($request);
}
}
example output:
Title: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
Message: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
x: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
y: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
based on this I only want that it only store:
Title:only save title
Message:save message
x:save x
y save y
Just pass in the whole array of hotspots like:
data: hotspots,
Then in your model do any formatting and insert many:
// some formatting to create data array
$data = [];
foreach($hotspots as $hotspot){
$data[] = [
'Title' => $hotspot['Title'],
'Message' => $hotspot['Message'],
'x' => $hotspot['x'],
'y' => $hotspot['y'],
];
}
Pin::insert($data);
The problem appears to be parsing of data to hotspots. This method is iterating over each entry of data, then assigning the full node.
$.each(data, function(index, node) {
hotspots.push(node);
});
Each property definition is using the full hotspots object, as opposed to one property.
data: {
Title: JSON.stringify(hotspots),
Message: JSON.stringify(hotspots),
x: JSON.stringify(hotspots),
y: JSON.stringify(hotspots),
},
You probably need to do something like this:
{
Title: hotspots[0].Title,
Message: hotspots[0].Message,
x: hotspots[0].x,
y: hotspots[0].y,
}
Even still, this solution is missing some important information. For example, hotspots should be an array of hotspot objects...how do you know which one you are going to send for the single request?

Trigger function in moment column is sorted in GridX

I use SingleSort module with Gridx. I can't find (I already checked SingleSort documentation and found nothing) a way to react on sort event. I need info about which (and how) column is sorted. I know how get info about sorting (getSortData method) but i don't know how make react in moment sort is made. I can't made onRender-event function because after sorting i will send that info to webapi get new data and again render Grid so event will be triggered again.
define([
"dojo/Evented",
"dojo/_base/declare",
"dojo/store/Memory",
"gridx/core/model/cache/Sync",
"gridx/Grid",
"gridx/modules/ColumnResizer",
'gridx/modules/Focus',
'gridx/modules/RowHeader',
'gridx/modules/select/Row',
'gridx/modules/select/Column',
'gridx/modules/select/Cell',
"gridx/modules/SingleSort"
], function (Evented, declare, Memory, Cache, Grid, ColumnResizer, Focus, RowHeader, SelectRow, SelectColumn, SelectCell, Sort) {
return declare([Evented], {
_counter: 1,
_topOffset: 100,
constructor: function () {
},
initialize: function () {
this._initGrid();
this._resizeGridContainer();
},
clear: function () {
var store = new Memory({ data: [] });
this._grid.setStore(store);
this._counter = 1;
},
_initGrid: function () {
var _this = this;
var store = new Memory({
data: []
});
var structure = [
{
id: 'operationType', field: 'operationType', name: dojo.byId(this._operationTypeId).value
},
{
id: 'transportationType', field: 'transportationType', name: dojo.byId(this._transportationUnitTypeId).value
},
{
id: 'transportationTypeLength', field: 'transportationTypeLength', name: dojo.byId(this._transportationLengthId).value
}
]
this._grid = Grid({
id: this._gridId,
cacheClass: Cache,
store: store,
structure: structure,
modules: [
ColumnResizer,
Sort
],
selectRowTriggerOnCell: true
});
this._grid.placeAt(this._gridPlaceholderId);
this._grid.startup();
},
_resizeGridContainer: function () {
var _this = this;
var container = dojo.byId(this._gridContainerId);
var height = container.parentElement.clientHeight - this._topOffset;
require(["dojo/dom-style"], function (domStyle) {
domStyle.set(_this._gridContainerId, "height", height + "px");
})
},
});
});
you need to tap on to the gridx SingleSort module sort method like this
this._grid.connect( this._grid.Sort, 'sort', function(colId, isDescending, skipUpdateBody){
alert(colId+" "+isDescending+" "+skipUpdateBody);
});
this will trigger the event whenever a grid column is sorted. Hope this helps.

Materialize chips initialization

I would like to add dynamically some materialize chips.
$('.chips-initial').material_chip({
data: [{
tag: 'Apple'
}, {
tag: 'Microsoft'
}, {
tag: 'Google'
}]
});
Like above but the values I want to give are dynamic.
How can I create an data object like above to pass it as parameter?
Thank you in advance
Basically what happens here is when the page loads it populates the text string values found in metaTags that were inserted into a hidden field from the database. The for loop iterates into the necessary chips-initial.
var tagsMeta = [];
//alert(tagsMeta);
var tagsString = document.getElementById('metaTags').value;
//alert(tagsString);
var tagsArray = tagsString.split(',');
for(i=0; i < tagsArray.length; i++) {
tagsMeta.push({tag: tagsArray[i]});
}
$('.chips-initial').material_chip({
data: tagsMeta
});
As I commented, you could create your own array of values and pass that to data. This might look like:
var myData = [
{
tag: 'iPhone'
}, {
tag: 'Windows Phone'
}, {
tag: 'Android Phone'
}
];
$('.chips-initial').material_chip({
data: myData
});
Wokring Example: https://jsfiddle.net/Twisty/en6r0ucb/
I found solution
var authData = [];
var tag = {};
tag["tag"] = yourString;
authData.push(tag);
$('.chips-initial').material_chip({
data: authData
});

Perserving a this. reference [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
My problem is that I have a grid that has an option to create a new row. This action sends an ajax request to my backend that inserts new rows into my Database. When completed it returns the MAX index (the most recently added index) to my frontend. I want to use this index as the value in ASSERTION_ID. So I need to wait for ajax request to finish and then update the grid with the created index.
The problem is that when I'm using a when(). then(). or simply the success callback for passing the data to my newRow then the .this part of this.state.rows and this.setState points to the "wrong" this. So how can you make sure that a task is completed while still perserving the same this. reference?
handleAddRow: function(e) {
var newAssertionID;
$.when($.ajax({
url: root + port + "/insertannotation",
type: 'post',
success: function(data) {
newAssertionID = data.assertionID.rows[0][0]
}
})).then(function(data) {
var newRow = {
ASSERTION_ID: newAssertionID
};
var rows = React.addons.update(this.state.rows, { $push: [newRow] });
this.setState({ rows: rows });
});
},
render: function() {
return (
React.createElement(ReactDataGrid, {
contextMenu: React.createElement(MyContextMenu, {
onRowDelete: this.deleteRow
}),
enableCellSelect: true,
onGridSort: this.handleGridSort,
columns: columns,
rowGetter: this.rowGetter,
rowsCount: this.getSize(),
minHeight: 500,
onRowUpdated: this.handleRowUpdated,
toolbar: React.createElement(Toolbar, {
enableFilter: true,
onAddRow: this.handleAddRow
}),
onAddFilter: this.handleFilterChange
})
);
}
You have to have a reference saved.
handleAddRow: function(e) {
var that = this; // note this
var newAssertionID;
$.when($.ajax({
url: root + port + "/insertannotation",
type: 'post',
success: function(data) {
newAssertionID = data.assertionID.rows[0][0]
}
})).then(function(data) {
var newRow = {
ASSERTION_ID: newAssertionID
};
var rows = React.addons.update(that.state.rows, {
$push: [newRow]
});
that.setState({
rows: rows
});
});
},

Defining multiple instances of a jquery ui widget on a single page

I am developing a website where I use a custom build jQuery widget to load data into multiple divs.
This is the code for the widget:
(function ($, window, document, undefined) {
$.widget ("my.contentloader", {
options: {
loading_message: true
},
_create: function () {
var that = this;
$.ajax ({
type: "POST",
url: that.options.url,
data: {data: that.options.formdata, limit: that.options.limit, offset: that.options.offset},
beforeSend: function (html) {
if (that.options.loading_message) {
$(that.options.target_area).html ("<div id='loading'>Loading</div>");
}
},
success: function (html) {
if (that.options.loading_message) {
$('#loading').remove ();
}
$(that.options.target_area).html (html);
},
error: function (html) {
$(that.options.error_area).html (html);
}
});
},
_setOption: function (key, value) {
this.options[key] = value;
$.Widget.prototype._setOption.apply (this, arguments);
}
});
})(jQuery, window, document);
I load data using the widget like this:
$('#targetdiv').contentloader ({
url: '<?php echo $action_url; ?>',
target_area: '#popup_box',
formdata: {'username' : username_email, 'password' : password}
});
I am having problems loading multiple instances on the same page.
Is there a way to not instantiate the widget on a specific div like this?
$('#targetdiv').contentloader
I think you need to assign each instance to a variable. That way, you can control each instance, or write a function that iterates over an array of instances.
var contentLoaders = [];
$('.target-div').each(function(i, data) {
contentLoaders[i] = $.widget("my.contentloader", { ... });
});
So then you should be able to operate on each loader independently, like:
for (var i in contentLoaders) {
var contentLoader = contentLoaders[i];
contentLoader.option( ... );
}
Also, you're using the DOM ID $('#loading') for multiple instances of the widget. This is wrong. You need to either use separate loaders for each widget, or else check to see if the ID exists and only insert the new node if it doesn't exist. And same for removing it.
** I've added this example block, hope it helps: **
//
// This is a way to do it if you want to explicitly define each contentloader.
// Below that, I'll write out a way to define the contentloaders in a loop.
//
var contentLoader1 = $('#targetdiv1').contentloader ({
url: '<?php echo $action_url; ?>',
target_area: '#popup_box',
formdata: {'username' : username_email, 'password' : password}
});
contentLoader1.option('url', 'http://google.com');
var contentLoader2 = $('#targetdiv2').contentloader ({
url: '<?php echo $action_url; ?>',
target_area: '#popup_box',
formdata: {'username' : username_email, 'password' : password}
});
contentLoader2.option('url', 'http:/apple.com');
// Push each widget instance into an array of widget objects
var contentLoaders = [];
contentLoaders.push(contentLoader1);
contentLoaders.push(contentLoader2);
for (var i in contentLoaders) {
console.log(i, contentLoaders[i].option('url'));
}
// Should print:
// 0 http://google.com
// 1 http://apple.com
//
//
// How to set a bunch of widgets at once from an array of content loader data
//
//
var contentLoaderData = [
{
divid: '#targetDiv1',
url: 'google.com',
formdata: {
username: 'joeshmo',
password: 'joeshmo1'
}
},
{
divid: '#targetDiv2',
url: 'apple.com',
formdata: {
username: 'plainjane',
password: 'plainjane1'
}
}
];
// Array of widget instances
var contentLoaders = [];
$.each(contentLoaderData, function(index, value) {
var contentLoader = $(this.divid).contentloader({
url: this.url,
target_area: '#popup_box',
formdata: {'username' : this.formdata.username, 'password' : this.formdata.password}
});
// Push each contentLoader instance into the contentLoaders array
contentLoaders.push(contentLoader);
});
for (var i in contentLoaders) {
console.log(i, contentLoaders[i].option('url'));
}
// Should print:
// 0 http://google.com
// 1 http://apple.com

Categories

Resources