nested object is undefined - Ajax call Response - Json Parser - ajax

My Ajax call is as follows
function onMapClick(e) {
$.ajax({
type: "GET",
url: GET_MAP_PT_INFO_URI,
data: { "lat": e.latlng.lat, "lng": e.latlng.lng },
dataType: 'json',
success: function (d) {
LoadPointDetails(d);
},
error: function () {
if (debugState) console.log("Error in call for chart data.");
}
});
}
function LoadPointDetails(obj) {
currPointDet = obj;
var objParsed = JSON.parse(obj);
console.log(objParsed);
...
}
My console log returns the following Json:
{"general" : {"id" : 45423920, "timestamp" : "2019-06-30T23:41:38.2", "run_id" : 29211, "track_id" : 10317, "link_id" : 983544872, "dir" : "T", "vehicle_name" : "Transporter", "prev_id" : 45423919, "next_id" : 45423921, "track_start" : "2019-06-30T23:31:12.7", "track_end" : "2019-07-01T00:34:15.6", "img_path" : "https://xyz-abc.s3-ap-southeast-2.amazonaws.com/somecode/1/123444.jpg", "notes" : null, "flag" : null}, "spatial" : {"lat" : -23.7830482, "lng" : 133.877221, "bearing" : 165, "speed_can_kmh" : 82, "speed_sat_kmh" : 81, "vert_velocity" : 0}, "line_data" : {"line_0_type_l" : "solid", "line_0_type_r" : "dashed", "line_0_qual_l" : "excellent", "line_0_qual_r" : "high", "line_0_width_l" : 0.13, "line_0_width_r" : 0.16, "line_1_type_l" : "solid", "line_1_type_r" : "solid", "line_1_width_l" : 0.14, "line_1_width_r" : 0.21, "line_2_type_l" : "dashed", "line_2_type_r" : "dashed", "line_2_width_l" : 0.00, "line_2_width_r" : 0.00, "ldw_left_on" : false, "ldw_right_on" : false, "ldw_off" : false, "ldw_left_avail" : true, "ldw_right_avail" : true}, "sign_data" : {"sign_type_1" : null, "sign_type_2" : null, "sign_type_3" : null, "sign_type_4" : null, "sign_type_5" : null, "sign_type_6" : null, "sign_type_7" : null}, "previous_sign_data" : {"sign_type_1" : 9, "sign_type_2" : 9, "sign_type_3" : 0, "sign_type_4" : 0, "sign_type_5" : 0, "sign_type_6" : 0, "sign_type_7" : 0}, "GeoJson" : {"type":"Feature","geometry":{"type":"Point","coordinates":[133.877221,-23.7830482]},"properties":{"id":45423920}}}
but when i try to access objParsed.general it is undefined
I want to read img_path.
What am I missing?

maybe you can get it directly:
function LoadPointDetails(obj) {
var img = obj.general.img_path;
alert(img);
}
In my test, I have an api:
public IActionResult getData()
{
var b = new { id = "45423920", img_path = "https://xyz-abc.s3-ap-southeast-2.amazonaws.com/somecode/1/123444.jpg" };
var c = new { lat = -23.7830482, lng = 133.877221 };
var a = new { general = b, spatial = c };
return Json(a);
}
Then my Ajax call:
$("#btn3").click(function() {
$.ajax({
type: "GET",
url: 'https://localhost:7151/home/getData',
data: { "lat": 111, "lng": 222 },
dataType: 'json',
success: function (d) {
LoadPointDetails(d);
},
error: function () {
if (debugState) console.log("Error in call for chart data.");
}
});
})

I found my answer here
My JSon was double encoded:
function LoadPointDetails(obj) {
currPointDet = obj;
var objParsed = JSON.parse(obj.trim());
var obj2 = JSON.parse(objParsed);
console.log(obj2.general);
}
This worked!

Related

How to get current sort field in kendo grid?

I'm beginner...
I'm using kendo-grid with Jquery.
I want to get current sorted field in kendo-gird.
I found this.
console.log(grid.dataSource._sort[0].dir);
console.log(grid.dataSource._sort[0].field);
Can I find alternative way?
this is my code.
var dataSource = new kendo.data.DataSource({
transport : {
read : {
type : 'post',
dataType : 'json',
contentType : 'application/json;charset=UTF-8',
url : cst.contextPath() + "/watcher/kendoPagination_statsErrorHistoryRetrieveQry.htm",
data : param
},
parameterMap: function (data, opperation) {
return JSON.stringify(data);
}
},
schema : {
data : function(data) {
return data;
},
total : function(response) {
return response.length > 0 ? response[0].TOTAL_COUNT : 0;
}
},
pageSize : cst.countPerPage(),
serverPaging : true,
serverSorting : true
});
var columns = kendoGridColumns();
$("#grid")
.kendoGrid({
dataSource : dataSource,
sortable : {
mode : 'multiple',
allowUnsort : true
},
columns : columns.error()
selectable : 'row',
scrollable : true,
resizable : true,
}));
How can I get current sorted field name?
Avoid using private fields. The DataSource sort method is the official way to get the current sort state:
http://docs.telerik.com/kendo-ui/api/javascript/data/datasource#methods-sort
var dataSource = new kendo.data.DataSource({
data: [
{ name: "Jane Doe", age: 30 },
{ name: "John Doe", age: 33 }
],
sort: { field: "age", dir: "desc" }
});
var sort = dataSource.sort();
console.log(sort.length); // displays "1"
console.log(sort[0].field); // displays "age"

Extjs- Grid column sorting case insensitive

I am having a grid populated with search results. The sorting seems to be working fine if all the values in each column are numbers or if all of them are in the same case(upper or lower). But some of the columns in my grid like firstname and lastname are a mix of uppercase, lowercase and empty values. When I click on that particular header for sorting purpose, these values seems to be sorted as case sensitive. The uppercase values come one by one, then there are a mix of empty values and then the lowercase values. I want this sorting to be done as case insensitive alphabetically. I think extjs sorts these values based on the ascii values. Is there any way I can overwrite this functionality and where should I be doing that.
For example, I have some values like james, JAMESON and ROBERT. When I click on top of the header, if it ascending, I should be getting james, JAMESON and Robert and all the empty/null values together at the top or bottom. But that is not happening. I am getting some empty values on the top and then JAMESON, james, empty value again , ROBERT followed by empty/null values. How can I make sure all the null values are grouped together and the sorting should be case insensitive.
{
header: "User Last Name",
width: 170,
dataIndex: 'userLastName'
},
{
header: "User First Name",
width: 170,
dataIndex: 'userFirstName'
},
Thanks,
On the field in your model, define a sortType,
http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Field-cfg-sortType
either as a function or as one of the predefined strings:
http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.SortTypes
I would guess that asUCText would be a good start, but I don't know what happens to null values there...
var itemsPerPage = 10; // set the number of items you want per page
var data = {
"success" : true,
"users" : [{
"id" : 1,
"name" : 'ed',
"email" : "ed#sencha.com"
}, {
"id" : 2,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 3,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 4,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 5,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 44,
"name" : '1',
"email" : "tommy#sencha.com"
},
{
"id" : 45,
"name" : '2',
"email" : "tommy#sencha.com"
},
{
"id" : 11,
"name" : 'Ed',
"email" : "ed#sencha.com"
}, {
"id" : 12,
"name" : 'apple',
"email" : "tommy#sencha.com"
},
{
"id" : 13,
"name" : 'Apple',
"email" : "tommy#sencha.com"
},
{
"id" : 14,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 15,
"name" : 'tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 21,
"name" : 'Ed',
"email" : "ed#sencha.com"
}, {
"id" : 22,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 23,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 24,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
{
"id" : 25,
"name" : 'Tommy',
"email" : "tommy#sencha.com"
},
]
}
Ext.apply(Ext.data.SortTypes, {
asPerson : function (name) {
// expects an object with a first and last name property
console.log("Test");
return name.toUpperCase() + name.toLowerCase();
}
});
var store = Ext.create('Ext.data.Store', {
autoLoad : true,
fields : [{
name : 'name',
sortType : 'asPerson'
}, {
name : 'email'
// sortType set to asFloat
}
],
pageSize : itemsPerPage, // items per page
data : data,
proxy : {
type : 'memory',
enablePaging : true,
reader : {
type : 'json',
root : 'users',
successProperty : 'success'
}
},
sorters : [{
property : 'name',
direction : 'ASC'
}
],
});
//Ext.Ajax.request({
// loadMask: true,
// url: 'app/data/users.json',
//
// success: function(resp) {
// // resp is the XmlHttpRequest object
// var options = resp.responseText;
//
//
//
// store.loadData(options);
// }
//});
//
//
Ext.define('AM.view.user.list', {
extend : 'Ext.grid.Panel',
alias : 'widget.userlist',
title : 'All Users',
initComponent : function () {
Ext.create('Ext.grid.Panel', {
title : 'My Test Demo',
store : store,
columns : [{
header : 'ID',
dataIndex : 'id'
}, {
header : 'Name',
dataIndex : 'name'
}, {
header : 'Email',
dataIndex : 'email',
flex : 1
}
],
width : 350,
height : 280,
dockedItems : [{
xtype : 'pagingtoolbar',
store : store, // same store GridPanel is using
dock : 'bottom',
displayInfo : true,
pageSize : 5,
}
],
renderTo : Ext.getBody()
});
this.callParent(arguments);
}
});
In ExtJS5 I add a transform to the sorter, e.g.
sorters: {
transform: function(item) {
return item.toLowerCase();
},
property: 'category_name'
}

Custom validation with ajax.....Here remote method is not working

I am using jquery.validate.js, in the code below both remote and regex works separately but when I try to integrate both then it is not working. Can anybody help me where I did wrong?
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#clear").click(function(){
$("input[type=text], textarea").val("");
});
});
function submitForm() {
$.validator.addMethod("subTitleVal", function(value, element) {
return this.optional(element) || /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement : function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules : {
name : {
required : true,
subTitleVal : true,
remote: {
type: 'POST',
url: "${pageContext.request.contextPath}/company/getDuplicate",
data: {"name":name},
dataType : "json",
success:function(data){
/* response = ( data == true ) ? true : false; */
if (data.name == true)
{
message: {
name: 'The username is already in use!'
}
}
}
},
}
},
},
errorElement : "span",
wrapper : "span",
messages : {
name : {
required : "Name Is Required",
}
}
});
if(validator.form()){
$('form#company').submit();
}
};
</script>
</head>
<body>
<form:form commandname="company" action="${pageContext.request.contextPath}/company/create.action" method="post" modelAttribute="company" name="theform">
<label>Name:</label>
<form:input path="name" id="name"></form:input>
Add
</form:form>
</body>
please help. Thanks
replace your code with this
function submitForm() {
$.validator.addMethod("subTitleVal", function(value, element) {
return this.optional(element)
|| /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement : function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules : {
name : {
required : true,
subTitleVal : true,
remote : {
type : 'POST',
url : "${pageContext.request.contextPath}/company/getDuplicate",
data : {
name: function() { return $("#name").val(); }
}
}
}
},
errorElement : "span",
wrapper : "span",
messages : {
name : {
required : "Name Is Required",
remote : "Name Already Taken."
}
}
});
if (validator.form()) {
$('form#company').submit();
}
};
From the documentation
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements, using
the default message; or a string, eg. "That name is already taken, try
peter123 instead" to display as the error message.
So your validation url must return an appropriate value
Try
function submitForm() {
$.validator.addMethod("subTitleVal", function(value, element) {
return this.optional(element)
|| /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement : function(error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules : {
name : {
required : true,
subTitleVal : true,
remote : {
type : 'POST',
url : "${pageContext.request.contextPath}/company/getDuplicate",
data : {
"name" : name
}
}
}
},
errorElement : "span",
wrapper : "span",
messages : {
name : {
required : "Name Is Required"
}
}
});
if (validator.form()) {
$('form#company').submit();
}
};
Your brackets are not closed properly. You have an extra },
Keep your code well-indented to avoid such minor mistakes in the future.
This should be your code instead:
function submitForm() {
$.validator.addMethod("subTitleVal", function (value, element) {
return this.optional(element) || /^[A-Za-z\s\_,\.:;()''""]+$/.test(value);
}, "Enter Valid Name.");
var validator = $("#company").validate({
errorPlacement: function (error, element) {
offset = element.offset();
error.insertBefore(element)
error.addClass('message');
error.css('position', 'absolute');
error.css('left', offset.left + element.outerWidth());
},
rules: {
name: {
required: true,
subTitleVal: true,
remote: {
type: 'POST',
url: "${pageContext.request.contextPath}/company/getDuplicate",
data: {
"name": name
},
dataType: "json",
success: function (data) {
/* response = ( data == true ) ? true : false; */
if (data.name == true) {
message: {
name: 'The username is already in use!'
}
}
}
},
}
},
errorElement: "span",
wrapper: "span",
messages: {
name: {
required: "Name Is Required",
}
}
});
if (validator.form()) {
$('form#company').submit();
}
};

jqplot changes the color of graph on mouse hover when graph has many data points

$.jqplot(
this.loadAvgChartId,
loadAvgChartData,
{
height : 130,
width : 410,
fontSize : '9px',
seriesColors : [ '#3aa5dc',
'#032ecf' ],
series : [ {
label : 'Load-5',
showMarker : false,
lineWidth : 1,
shadowDepth : 0,
shadowOffset : 1.25,
}, {
label : 'Load-15',
showMarker : false,
lineWidth : 1,
shadowDepth : 0
} ],
legend : {
show : false
},
grid : {
gridLineColor : '#EBEBEB',
gridLineWidth : 1.0,
show : false,
shadow : false,
shadowDepth : 0,
background : '#FFF',
drawBorder : false,
borderColor : '#999',
borderWidth : '1.0'
},
cursor : {
zoom : false,
showToolTip : false,
showVerticalLine : false,
showCursorLegend : false,
intersectionThreshold : 20,
style: 'default'
},
highlighter : {
bringSeriesToFront: this.isIE7?false:true,
shadow : false,
lineWidthAdjust: 1,
sizeAdjust: -3,
tooltipLocation: 'n',
tooltipAxes: 'both',
formatString: '<i>%s</i><br/><b>%s</b>',
useAxesFormatters : true
},
axes : {
xaxis : {
renderer : $.jqplot.DateAxisRenderer,
syncTicks : true,
tickOptions : {
showGridline : true,
formatString : this.nmdLoadAvgs[this.selectedLoadAvg].curTickFormatString
},
labelPosition : 'start',
tickInterval : this.nmdLoadAvgs[this.selectedLoadAvg].curTickInterval,
min : minXaxisTick,
max : maxXaxisTick
},
yaxis : {
tickOptions : {
showGridline : false,
showMark : false
},
//tickInterval : .5,
pad: 1.4,
min : 0.0,
max: maxYaxisTick,
numberTicks: 3
}
}
}
);
this worked for me:
jqplot changes the color of graph on mouse hover
seriesDefaults:
{
rendererOptions:
{
highlightMouseOver: false
}
}

DataTable + JEditable + AutoComplete(BAssistance) + Server Side Processing

After almost struggling for a week I have been able to make DataTable + JEditable + AutoComplete(BAssistance) with server side processing using Json to work.
I thought it would be useful to somebody out there.
$(document).ready(function() {
$('#example tbody td').editable(
function(value, settings) {
processEventForTable(this, value);
return(value);
},
"height": "20px"
});
oTableexample = $('#example').dataTable({
"bInfo": true,
"bProcessing" : true,
"bServerSide" : true,
"sAjaxSource" : "GetPaginationData.aspx",
"sPaginationType": "full_numbers",
"bPaginate" : true,
"fnServerData": function ( sSource, aoData, fnCallback ) {
var data = {"name" : "kObjectId",
"value" : definitionId};
aoData.push(data);
data = { "name" : "ObjectName", "value" : "example" };
aoData.push(data);
data = { "name" : "InstanceId", "value" : instanceId };
aoData.push(data);
data = { "name" : "IsNewRequest", "value" : IsNewRowAdded};
IsNewRowAdded = 0;
aoData.push(data);
debugger;
$.ajax( {
"dataType": 'json',
"type": "Get",
"url": sSource,
"data": aoData,
"success": fnCallback
});
},
"fnDrawCallback" : function() {
debugger;
SetDataTableIDAndAttachJEditable("example");
$('#example tbody td').editable( function(value, settings)
{
var aPos = oTableexample.fnGetPosition( this );
processEventForTableNew(aPos[0], aPos[1], value, "example");
return(value);
}
);
}
});
$.editable.addInputType('autocomplete', {
element : $.editable.types.text.element,
plugin : function(settings, original) {
$('input', this).autocomplete(settings.autocomplete.url, {
dataType:'json',
parse : function(data) {
return $.map(data, function(item) {
return {
data : item,
value : item.Key,
result: item.value
}
})
},
formatItem: function(row, i, n) {
return row.value;
},
mustMatch: false,
focus: function(event, ui) {
$('#example tbody td[title]').val(ui.item.label);
return false;
}
});
}
});
$("#example tbody td > span[title]").editable(
function(value,settings){
return value;
},
{
type : "autocomplete",
tooltip : "Click to edit...",
autocomplete : {
url : "autocompleteeg.aspx"
}
}
);
});
This code works perfectly fine.
DataTables use Server Side Processing. And I am submitting the changes to JEditable to javascript function. From there on Submit I am submitting the entire change array to server.
This code has become too long can anybody help me refactor it.
If there is any better way to accomplish the same thing then I am waiting for it. :)
Yeah cool Dude !
Just a small syntax error in your code.
} , { // opening bracket missing
"height": "20px"
}
Thanks a lot

Resources