Uncaught ReferenceError with a seemingly defined variable - javascript

So I have this template that utilizes KendoUI to render a grid. Here's a part of it:
<script id="rowTemplateCourse" type="text/x-kendo-tmpl">
<tr data-cid="#: id #" class="course-row" id="course-row#: id #">
<td>
<span class="circle-indicator label-#if(package_is_active == 1){#success#}else{#danger#}#"></span>
</td>
<td>
#: course_name # - #= name#
</td>
<td>
<span class="badge element-bg-color-blue">ver. #:version_number#</span>
</td>
</tr>
</script>
I get the needed information from a php controller, that loads a variable in my view that holds this template. Variable holds this sort of data:
[1] => Array(
[id] => 544
[course_name] => Course for whatever
[price] => 52
[logo] => assets/images/new_course.png
[version_number] => 1
[parent_version_id] => 0
[course_price] => 52.00
[description_for_school] =>
[is_print_only] => 0
[offer_pdf] => 0
[pdf_final_price] => 0.00
[simple_course] => 0
[state_id] => 50
[name] => Tennessee
[cs_days_to_complete] => 120
[course_is_active] => 1
[user_in_course] => no
[user_is_waiting] => no
[days_to_complete] => 0)
In my view, I parse this variable like so:
var course_data = JSON.parse('<?php print(json_encode($courses));?>');
This works correctly and returns the same data like so (copy from console.log):
1: Object
course_is_active:"1"
course_name:"Course for whatever"
course_price:"52.00"
cs_days_to_complete:"120"
days_to_complete:0
description_for_school:""
id:"544"
is_print_only:"0"
logo:"assets/images/new_course.png"
name:"Tennessee"
offer_pdf:"0"
parent_version_id:"0"
pdf_final_price:"0.00"
price:"52"
simple_course:"0"
state_id:"50"
user_in_course:"no"
user_is_waiting:"no"
version_number: "1"
I load the data in a grid like so:
var courses_grid = $("#courses_grid").kendoGrid({
dataSource: {
data: course_data,
schema: {
model: {
fields: {
id: {
type: "number"
},
course_name: {
type: "string"
},
course_short_description: {
type: "string"
}
}
}
},
pageSize: 10,
},
toolbar: kendo.template($("#course-header-template").html()),
rowTemplate: kendo.template($("#rowTemplateCourse").html()),
groupable: false,
sortable: true,
selectable: "single",
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
title: "Status",
width: 100
}, {
title: "Course Name",
}]
});
When the page loads, I get an error that course_is_active is not defined. I don't see how it's not defined, as it is clearly here and has a value. Can someone help me figure this out?
More info on the error:
Uncaught ReferenceError: course_is_active is not defined
(function(data
/**/) {
var $kendoOutput, $kendoHtmlEncode = kendo.htmlEncode;with(data){$kendoOutput='\n\t <tr data-cid="'+$kendoHtmlEncode( id )+'" class="course-row" id="course-row'+$kendoHtmlEncode( id )+'">\n <td>\n <span class="circle-indicator label-';if(course_is_active == 1){;$kendoOutput+='success';}else{;$kendoOutput+='danger';};$kendoOutput+='"></span>\n </td>\n\t\t <td>\n '+$kendoHtmlEncode( course_name )+' - '+( name)+'\n\t\t </td>\n\t\t\t<td>\n <span class="badge element-bg-color-blue">ver. '+$kendoHtmlEncode(version_number)+'</span>\n\t\t </td>\n\t </tr>\n\n';}return $kendoOutput;
})

I have found the problem. In my PHP code, I am checking in the arrays if a value is equal to 0 and if it is, I am removing that element from the array. This happens to be the first element in the 2D array I load in the view, so when KendoUI starts to load variables in the table, it starts with the [0] index, that does not exist, and throws an error. Thanks to everyone that participated.

Related

Vue V-for in tables

I am trying to create tables using the v-for directive, but I wanted to know if there is any way to do some conditionals inside the individual tables based on a certain value. I am including a generic version of what I have as my data and what I am trying to produce.
Data Example (this is what I am pulling in from the API call):
MainOrg
SubOrgId
SubOrgName
SubOrgState
TotalOrgs
10110
101101
Main Office
AK
26
10110
101102
Branch Office
AK
4
10110
101102
Sat Office
AK
2
10111
101111
Main Office
FL
26
10111
101112
Branch Office
FL
4
10111
101112
Sat Office
FL
2
I am trying to loop through the "MainOrg" column and create a new table for each unique one, then have the data that corresponds to that "MainOrg" in the output table. The "MainOrg" would become the title for the table.
The output I am trying to get is as follows:
10110
SubOrgId
SubOrgName
SubOrgState
TotalOrgs
101101
Main Office
AK
26
101102
Branch Office
AK
4
101102
Sat Office
AK
2
10111
SubOrgId
SubOrgName
SubOrgState
TotalOrgs
101111
Main Office
FL
26
101112
Branch Office
FL
4
101112
Sat Office
FL
2
I have been running into the following issues with the v-for and v-if directives:
**Duplicates main orgs due to it being based on index
<table v-for="(d, index) in data" :key="index">
<thead>
<tr>
<th>{{ d.MainOrg }}</th>
</tr>
</thead>
I really want it to spit out a new table for each unique "MainOrg", then contextually look at my data to include the "SubOrg" data that matches it, per my desired result above. I have not been able to find the right combination of Vue Html and/or JavaScript that can create the desired result based on the need for the data to be separated into individual tables. Also, within the table elements, I am unsure of how to reference the index of the data for conditionals. For example, when I tried using v-if instead of v-for to create the tables by accessing a unique array of the MainOrgs, I did not know how to contextually tie the data together.
In non-programmer speak/pseudo code: Take the unique MainOrg values from data and create a new table for each MainOrg. Then, take the remaining columns/rows from data and add them to each MainOrg table where the row context (data.MainOrg) matches the table for that MainOrg.
Apologies for the long post, but any help is greatly appreciated.
Edit
I am getting slightly different results from the two answers suggested as follows:
computed: {
regions: ({ estabSearchResult }) =>
estabSearchResult.reduce(
(map, { region, ...rest }) => ({
...map,
[region]: [...(map[region] ?? []), rest],
}),
{}
),
},
Some data shown is modified for sensitivity
Which gives me the following:
regions:Object
IN0110 - :Array[2]
IN0114 - :Array[1]
IN0115 - :Array[1]
IN0120 - :Array[1]
IN0130 - :Array[1]
IN0160 - :Array[1]
IN01BB - :Array[1]
IN28AO - :Array[1]
IN28BO - :Array[13]
The forEach() method(below)
if (this.estabSearchResult.length > 0) {
const newObj = {}
this.estabSearchResult.forEach(obj => {
newObj[obj.region] ?
newObj[obj.region].push(obj) : newObj[obj.region] = [obj]
})
this.estabRegionGroup = newObj
}
gives me the following:
estabRegionGroup:Object
IN0110 - :Array[3]
IN0114 - :Array[1]
IN0115 - :Array[1]
IN0120 - :Array[1]
IN0130 - :Array[1]
IN0160 - :Array[1]
IN01BB - :Array[1]
IN28AO - :Array[1]
IN28BO - :Array[13]
Notice the array size for IN0110. The forEach() gives me 3 objects in the array, where the reduce(map()) gives me only two. All other items/regions are the same and correct, only that first one is off. Any ideas? The results for IN0110 should have 3 objects in it.
Create a computed property to represent the new data structure
computed: {
regions: ({ estabSearchResult }) =>
estabSearchResult.reduce(
(map, { region, ...rest }) => ({
...map,
[region]: [...(map[region] ?? []), rest],
}),
{} // don't forget to init with an empty object
),
}
This looks something like
{
"10110": [{ SubOrgId: 101101, ... }, ...],
"10111": [{ SubOrgId: 101111, ... }, ...],
}
which you can then use in rendering
// Just some fake, random data using your "region" values
const fakeApi = {get:()=>new Promise(r=>setTimeout(r,1000,[{"region":"IN0110","foo":0.7051213449189915},{"region":"IN0110","foo":1.4213972602828675},{"region":"IN0110","foo":2.075397586536013},{"region":"IN0114","foo":0.7055750843380546},{"region":"IN0115","foo":0.5976362522109442},{"region":"IN0120","foo":0.6605446959279311},{"region":"IN0130","foo":0.7179704337235409},{"region":"IN0160","foo":0.19066097499077084},{"region":"IN01BB","foo":0.0019511615325726872},{"region":"IN28AO","foo":0.46443847116756487},{"region":"IN28BO","foo":0.41268230939585426},{"region":"IN28BO","foo":1.9572873014553014},{"region":"IN28BO","foo":2.610276341696757},{"region":"IN28BO","foo":3.7301898988777733},{"region":"IN28BO","foo":4.021495358709221},{"region":"IN28BO","foo":5.996280938563549},{"region":"IN28BO","foo":6.66092280472865},{"region":"IN28BO","foo":7.660937785660997},{"region":"IN28BO","foo":8.288195167562918},{"region":"IN28BO","foo":9.84101941796214},{"region":"IN28BO","foo":10.34450778678685},{"region":"IN28BO","foo":11.782972607317836},{"region":"IN28BO","foo":12.05067212727201}]))};
new Vue({
el: "#app",
data: () => ({
estabSearchResult: [],
}),
async created () {
this.estabSearchResult = await fakeApi.get();
},
computed: {
regions: ({ estabSearchResult }) =>
estabSearchResult.reduce(
(map, { region, ...rest }) => ({
...map,
[region]: [...(map[region] ?? []), rest],
}),
{}
),
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<p v-if="estabSearchResult.length === 0">Loading...</p>
<div v-for="(orgs, region) in regions" :key="region">
<p><strong>{{ region }} ({{ orgs.length }})</strong></p>
<table border="1">
<thead>
<tr>
<th>Foo</th>
</tr>
</thead>
<tbody>
<tr v-for="(org, index) in orgs" :key="index">
<td>{{ org.foo }}</td>
</tr>
</tbody>
</table>
</div>
</div>
First I think you have to convert your array of objects into an object of objects which contains MainOrg as key with the help of Array.forEach()
Like this :
const tableAllData = [{
MainOrg: 10110,
SubOrgId: 101101,
SubOrgName: 'Main Office'
}, {
MainOrg: 10110,
SubOrgId: 101102,
SubOrgName: 'Branch Office'
},{
MainOrg: 10110,
SubOrgId: 101102,
SubOrgName: 'Sat Office'
}, {
MainOrg: 10111,
SubOrgId: 101111,
SubOrgName: 'Main Office'
},{
MainOrg: 10111,
SubOrgId: 101112,
SubOrgName: 'Branch Office'
}, {
MainOrg: 10111,
SubOrgId: 101112,
SubOrgName: 'Sat Office'
}];
const newObj = {};
tableAllData.forEach(obj => {
newObj[obj.MainOrg] ?
newObj[obj.MainOrg].push(obj) : newObj[obj.MainOrg] = [obj]
});
console.log(newObj);
Live Demo with Vue :
new Vue({
el: '#app',
data: {
tableAllData: [{
MainOrg: 10110,
SubOrgId: 101101,
SubOrgName: 'Main Office'
}, {
MainOrg: 10110,
SubOrgId: 101102,
SubOrgName: 'Branch Office'
},{
MainOrg: 10110,
SubOrgId: 101102,
SubOrgName: 'Sat Office'
}, {
MainOrg: 10111,
SubOrgId: 101111,
SubOrgName: 'Main Office'
},{
MainOrg: 10111,
SubOrgId: 101112,
SubOrgName: 'Branch Office'
}, {
MainOrg: 10111,
SubOrgId: 101112,
SubOrgName: 'Sat Office'
}],
categorizedTable: {}
},
mounted() {
const newObj = {};
this.tableAllData.forEach(obj => {
newObj[obj.MainOrg] ?
newObj[obj.MainOrg].push(obj) : newObj[obj.MainOrg] = [obj]
});
this.categorizedTable = newObj;
}
})
table, thead, th, td, tr {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="item in Object.keys(categorizedTable)" :key="item">
<h3>{{ item }}</h3>
<table>
<thead>
<th>SubOrgId</th>
<th>SubOrgName</th>
</thead>
<tbody>
<tr v-for="(row, index) in categorizedTable[item]" :key="index">
<td>{{ row.SubOrgId }}</td>
<td>{{ row.SubOrgName }}</td>
</tr>
</tbody>
</table>
</div>
</div>

Vue.js: Return image with method after axios.get

<li v-for="people in projectData.employees" :key="people._id">
<b-img :src="colleagueImages(people)"
</li>
async colleagueImages(people) {
console.log(people); // => max#stackoverflow.com
let profileImage = await axios.get("http://myapilink.com/image?id=" + people + "&s=200&def=avatar", {
headers: {
'accept': 'image/jpeg'
}
});
console.log(profileImage);
return 'data:image/jpeg;base64,' + btoa(
new Uint8Array(profileImage.data)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
}
The console.log(profileImage) returns the following:
The API I am using is returning a Base64 Image.
With my current code I only get the following error in my browser console:
[Vue warn]: Invalid prop: type check failed for prop "src". Expected String, got Promise.
Since you don't have all the data you need to render in the first place, you have to change attributes afterwards. First, you need to use Vue components for your items, so your "src" attribute will be reactive; second, you start the requests for your items after you rendered your app. Please see this mockup.
Vue.component('todo-item', {
template: `
<li>
<label>
<input type="checkbox"
v-on:change="toggle()"
v-bind:checked="done">
<del v-if="done">
{{ text }}
</del>
<span v-else>
{{ text }}
</span>
<span v-if="like">
♥ {{like}}
</span>
</label>
</li>
`,
props: ['id', 'text', 'done', 'like'],
methods: {
toggle: function(){
this.done = !this.done
}
}
})
let todos = [
{id: 0, text: "Learn JavaScript", done: false, like: null },
{id: 1, text: "Learn Vue", done: false, like: null },
{id: 2, text: "Play around in JSFiddle", done: true, like: null },
{id: 3, text: "Build something awesome", done: true, like: null }
]
const v = new Vue({
el: "#app",
data: {
todos: todos
}
})
todos.forEach((item) => {
// This is just a mock for an actual network request
window.setTimeout(() => {
item.like = Math.ceil(Math.random() * 100)
}, Math.random() * 2000)
})
https://jsfiddle.net/willywongi/gsLqda2y/20/
In this example I have the basic todo-list app with a fake "like" count for each item, which is calculated asynchronously. After setting up my app, I wait for the "like" attribute values (in my example I just wait a random value of milliseconds).

Kendo Grid: Drag and Drop Cell Data From One Grid Into another

I have recently had an issue with Kendo MVC where I have needed to drag a product code from one Kendo Grid into another where the cell value is empty.
Scenario:
Grid A, products ordered, where the vendor sending the list of products doesnt have a full product list and 90% accurate descriptions.
Grid B, Products, with full \ correct descriptions and product codes.
I now need to populate Cell x in Grid A, with data from Cell Y in Grid B. In the current windows (WinForms) application, the user can use drag and drop.
Issue:
Kendo Grids do not easily provide a drag and drop feature.
Kendo themselves, admittedly a while back say this is not supported but produced a fiddle that would allow the dragging and dropping of a cell to re-order the row, and thats about it.
They also, never produced any scenario for ASP.Net MVC.
As this is something that I need, and also appears to be something that others may have searched for, you will see below the code in here to help someone who was \ is in my position, and a fiddle for the Kendo UI, and the MVC examples.
Because of how my project is organised and is using Typescript the MVC version isnt going to be 1:1 exact but will be close enough for someone to follow.
A few caveats on this is when you pick up the item, you can click anywhere on the row. (if anyone can refine this please post an answer, I will test and if it works I will upvote and also incorporate your answer with working code.
In addition to the above the dataItem that you pick up is picked up in a position relative to where the mouse is. This I will fix over time, but if anyone gets to this before me please feel free as above.
First,
Kendo UI Code
Html
<html>
<head>
<title>KendoUI Test Page</title>
<link href="//kendo.cdn.telerik.com/2018.3.1017/styles/kendo.common.min.css" rel="stylesheet" />
<script src="//code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="//kendo.cdn.telerik.com/2018.3.1017/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid"></div>
<div id="grid2"></div>
</body>
</html>
CSS
.hint {
padding: 7px 10px;
background-color: #FFFFFF;
}
**JavaScript \ JQuery **
var data = [
{ id: 1, text: "text 1", position: 0 },
{ id: 2, text: "text 2", position: 1 },
{ id: 3, text: "text 3", position: 2 }
]
var data2 = [
{ id: 4, text: "", position: 0 },
{ id: 5, text: "", position: 1 },
{ id: 6, text: "", position: 2 }
]
var dataSource = new kendo.data.DataSource({
data: data,
schema: {
model: {
id: "id",
fields: {
id: { type: "number" },
text: { type: "string" },
position: { type: "number" }
}
}
}
});
var dataSource2 = new kendo.data.DataSource({
data: data2,
schema: {
model: {
id: "id",
fields: {
id: { type: "number" },
text: { type: "string" },
position: { type: "number" }
}
}
}
});
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
scrollable: false,
columns: ["id", "text"]
}).data("kendoGrid");
var grid2 = $("#grid2").kendoGrid({
dataSource: dataSource2,
scrollable: false,
columns: ["id", "text"]
}).data("kendoGrid");
grid.table.kendoDraggable({
filter: "tbody > tr",
group: "gridGroup",
threshold: 100,
hint: function(e) {
var dataItem = grid.dataItem(e);
return $('<div class="hint">' + dataItem.text + '</div>').css({ marginLeft: e.clientX, marginTop: e.clientY });
}
});
grid2.table.kendoDropTarget({
group: "gridGroup",
drop: function(e) {
e.draggable.hint.hide();
var dest = $(document.elementFromPoint(e.clientX, e.clientY));
var row = dest.closest('tr')
var uid = row[0].dataset.uid
var originalVal = dest[0].innerHTML
var target = dataSource2.getByUid(uid)
var g = $("#grid2").data("kendoGrid")
$.each(g.dataSource.data(), function(idx, gridrow){
if(gridrow.uid === uid){
var dataItem = g.dataSource.get(gridrow.id)
dataItem.set("text", e.draggable.hint[0].innerHTML);
}
})
}
});
Fiddle
https://jsfiddle.net/SimonPrice/t2aju3c6/77/
MVC 5
Razor Partial
<div class="row">
<div id="divOrderedLines" class="col-md-6 col-sm-6 col-xs-6" hidden>
<div class="panel panel-default">
<div class="panel-heading">OrderedLines</div>
<div class="panel-body">
#Html.Partial("_orderedLines")
</div>
</div>
</div>
<div id="divProductLines" class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">Product Lines</div>
<div class="panel-body">
#Html.Partial("_productLines")
</div>
</div>
</div>
</div>
Ordered Lines \ Dropping \ Droppable Grid
#(Html.Kendo().Grid<zzzViewModel>
()
.Name("epsGrid")
.Columns(columns =>
{
//Columns removed
columns.Bound(c => c.ProductCode).HtmlAttributes(new { #class = "drop-target" });
})
.Events(evt => evt.DataBound("fe_rxManager.SetEpsTableOptions"))
.Events(evt => evt.Change("fe_rxManager.styleColumn"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
.ToolBar(toolbar =>
{
toolbar.Template(#<text><button id="btnNewOrder" class="btn btn-default" disabled="disabled">New Order <i class="fa fa-plus"></i></button></text>);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Ordered_Read", "RxManager"))
.PageSize(20)
)
)
Product Lines \ Draggable Grid
#(Html.Kendo().Grid<xxxViewModel>
()
.Name("rxGrid")
.Columns(columns =>
{
columns.Bound(c => c.OrderId).Visible(false);
columns.Bound(c => c.LineID).Visible(false);
columns.Bound(c => c.ProductCode).HtmlAttributes(new { #class= "product-code" });
columns.Bound(c => c.Quantity);
columns.Bound(c => c.CPQuantity);
columns.Bound(c => c.PQuantity);
columns.Bound(c => c.Description);
columns.Bound(c => c.OnHandQuantity);
})
.Events(evt => evt.DataBound("fe_rxManager.rxLinesDataChanged"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(true)
.ButtonCount(5)
)
.Editable(m => m.Mode(GridEditMode.InCell).DisplayDeleteConfirmation(false))
//.BindTo(#Model.xxxLines)
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Product_Read", "RxManager").Data("fe_rxManager.xxxLines_Read_AdditionalData"))
.Model(model =>
{
model.Id(l => l.xxxLineID);
model.Field(p => p.ProductCode).Editable(false);
model.Field(p => p.Description).Editable(false);
model.Field(p => p.Quantity).Editable(false);
model.Field(p => p.CPQuantity).Editable(false);
model.Field(p => p.PQuantity).Editable(true);
model.Field(p => p.PQuantityPrice).Editable(false);
model.Field(p => p.OnHandQuantity).Editable(false);
})
.PageSize(20)
))
Typscript \ JavaScript \ JQuery
SetEpsTableOptions = (e: any) => {
this.dragAndDrop();
this.hideLastColumn(); // Dont worry about this
this.styleColumn(e); // Dont worry about this
}
dragAndDrop = () => {
var rxGrid = $("#rxGrid").data("kendoGrid") as any;
rxGrid.table.kendoDraggable({
filter: "tbody > tr",
group: "gridGroup",
threshold: 100,
hint(e) {
var dataItem = rxGrid.dataItem(e);
return $('<div class="hint">' + dataItem.ProductCode + '</div>').css({ marginLeft: e.clientX, marginTop: e.clientY });
}
});
var epsGrid = $("#epsGrid").data("kendoGrid") as any;
epsGrid.table.kendoDropTarget({
group: "gridGroup",
drop(e) {
e.draggable.hint.hide();
var dest = $(document.elementFromPoint(e.clientX, e.clientY));
var row = dest.closest('tr');
var uid = row[0].dataset.uid;
$.each(epsGrid.dataSource.data(),
(idx, gridrow) => {
if (gridrow.uid === uid) {
var dataItem = epsGrid.dataSource.get(gridrow.id);
dataItem.set("ProductCode", e.draggable.hint[0].innerHTML);
}
});
}
});
}
Hopefully this post can help a few people out. Please feel free to leave positive comments that could either help improve this post.

getElementById("myID").value returns "Cannot read property 'value' of null" error and when I console log "myID" I get the whole class text

Here is my stateless function in which the user can put in a time value.
As you can see I am setting the ID for the input field with props.UserInputTimeID (I think this may be part of the error). This is because I want to reuse this component with different ID's.
const UserInputTime = (props) =>
{
return (
<div>
<form>
{props.UserInputTimeMessage}
<input type="time" id={props.UserInputTimeID} defaultValue={"00:01"} min="00:01" max={props.maxTime}></input>
<input onClick={props.userInputTimeHandler} type="submit" value="Send"></input>
</form>
</div>
)
};
In my container (App.js) where I call to render this component I set the prop values as shown below. My ID's are set to "studyTimer" and "breakTimer"
render() {
return (
<div >
<DisplayTimer UserInputTimeID={"studyTimer"}/>
<UserInputTime
UserInputTimeMessage={"Set the length of your study time from 1 - 59 minutes"}
UserInputTimeID={"studyTimer"}
maxTime={"00:59"}
userInputTimeHandler={{/* todo - placeholder for function */}}
/> {/*study timer*/}
{console.log("A test to see what the value is : " + UserInputTime)}
<DisplayTimer UserInputTimeID={"breakTimer"}/>
<UserInputTime
UserInputTimeMessage={"Set the length of your break from 1-20 minutes"}
UserInputTimeID={"breakTimer"}
maxTime={"00:20"}
userInputTimeHandler={{/* todo - placeholder for function */}}
/> {/*break timer*/}
</div>
);
}
In my component DisplayTimer I have the following code which is where the error is showing. It says that the value for the ID is null.
const DisplayTimer = (props) =>
{
let newTimerValue = document.getElementById(props.UserInputTimeID).value;
return(
<div>
</div>
)
};
When I looked at the console the statement I got back was weird:
A test to see what the value is : function UserInputTime(props) //todo check if this variable should use camelcase or pascalcase
{
return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("div", {
__source: {
fileName: _jsxFileName,
lineNumber: 6
},
__self: this
}, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("form", {
__source: {
fileName: _jsxFileName,
lineNumber: 7
},
__self: this
}, props.UserInputTimeMessage, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("input", {
type: "time",
id: props.UserInputTimeID,
defaultValue: "00:01",
min: "00:01",
max: props.maxTime,
__source: {
fileName: _jsxFileName,
lineNumber: 9
},
__self: this
}), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement("input", {
onClick: props.userInputTimeHandler,
type: "submit",
value: "Send",
__source: {
fileName: _jsxFileName,
lineNumber: 10
},
__self: this
})));
}

Datatable jquery serverside only work on the load page

I search in all web,i.e Google, datatable docs, datatable .. and not found the solution.
I use Symfony 4 and follow this text, https://datatables.net/examples/server_side/simple.html and https://datatables.net/manual/server-side. Then my code is that:
<html>
<table id="datatable" class="table table-striped table-bordered dataTable no-footer" role="grid" aria-describedby="datatable_info">
<thead>
<tr class="headings">
<th></th>
<th class="column-title">Número/Ano</th>
<th class="column-title">Cadastrado em</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
var table = $('#datatable').DataTable( {
"serverSide": true,
"info": true,
"stateSave": true,
"ajax":{
"url":"/decreto/filter",
"type": "GET"
},
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.16/i18n/Portuguese-Brasil.json"
},
"lengthMenu": [ 5, 10, 15, 25 ],
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{
"data": "number",
"render": function ( data, type, row ) {
var z = "";
data = data.toString();
for (;(4-data.length)>z.length;z = z.concat("0"));
return z+data+"/"+row.year;
},
},
{
"data":"registry.date",
"render": function ( data ) {
var dMy = data.split(" ")[0].split("-");
var time = data.split(" ")[1].split(".")[0];
return dMy[2]+"/"+dMy[1]+"/"+dMy[0]+" "+time;
},
},
],
//*/
"order": [[1, 'asc']]
} );
</script>
My Controller return that:
$source = $request->query->get("search")["value"];
$rows = $request->query->get("length");
....
return new JsonResponse(
array(
'draw'=>intval(1),
'recordsTotal'=>intval($em->total()["total"]),
'recordsFiltered'=>intval(count($list)),
'data'=>$list,
)
);
When the page load at first time, this work fine, return only 5 rows like I define. But if I try to filter, don't work.
For debug what was send, I change the method in Symfony, switch GET for Post, and return an error with the URL:
jquery.min.js:4 GET http://localhost:8000/decreto/filter?draw=1&columns%5B0%5D%5Bdata%5D=&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=false&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=number&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=registry.date&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=files&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=4&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=1&order%5B0%5D%5Bdir%5D=asc&start=0&length=5&search%5Bvalue%5D=el&search%5Bregex%5D=false&_=1520304436769 405 (Method Not Allowed)
Then I fix the method to filter the request sent, was send :
DecretoController.php on line 194:
array:7 [▼
"draw" => "1"
"columns" => array:5 [▶]
"order" => array:1 [▼
0 => array:2 [▶]
]
"start" => "0"
"length" => "5"
"search" => array:2 [▼
"value" => "el"
"regex" => "false"
]
"_" => "1520302968156"
]
The content is like says https://datatables.net/manual/server-side.
Oh right then, and continuous with the says the site above, my controller returned:
DecretoController.php on line 224:
array:4 [▼
"draw" => 1
"recordsTotal" => 6
"recordsFiltered" => 1
"data" => array:1 [▼
0 => array:13 [▶]
]
]
Data has 1 element, the match with i lookup. Until then, fine! The fine, finish here. Make the jsonResponse the change for:
{"draw":1,"recordsTotal":6,"recordsFiltered":1,"data":
[{"id":"XYgrQvzrYrYY","number":2,"year":2018,"publish":{"date":"2018-01-11 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"created":{"date":"2018-01-02 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"description":"asfasfasdfasdfsadfsadfsd (admitido pelo sdfasdf), o sr. sfasdfasfas.","registry":{"date":"2018-03-02 02:04:22.000000","timezone_type":3,"timezone":"UTC"},"active":1,"user_id":1,"user_first_name":"Eu,"unidade_id":7,"unidade_name":"Co do Munic\u00edpio","files":[]}]}
What's wrong?
- Load at first page OK
- Search is working
- Return like order on documentation
I use https://code.jquery.com/jquery-1.12.4.js
Thanks ..
:(
because you have fixed draw value, which should be sequence for every request.
explaination:
first load. datatables request draw=1. php return draw=1 . this works fine.
if you do any action (sort, search, filter etc). datatables will request draw=2. php return draw=1. error happened. because request draw is not match with response draw
try change 'draw'=>intval(1), to 'draw'=>intval($_GET['draw']),

Categories

Resources