I have json string retuned via a ajax call
$.ajax({
type: 'GET',
url: quoteURL,
dataType: 'json',
timeout: 10000,
crossDomain: true,
success: function(result) {
/// required code
}
});
The returned json response from server is
{
_emptyscopedata: [
{},
{}
],
errMsgBuffer: {
errMsg: ''
},
descriptor: [
{
template: 'projects/mobile/market/mostactives.xsl',
componentname: 'getmostactives'
},
{
template: '',
componentname: 'quotelist'
}
],
'invest.mostactive': {
MoverExchange: 'NSDQ',
MoverType: 'ACT',
urlType: ''
},
quotelist: {},
'quote.quote': [
{
timezoneid: 'EST',
change: '0.01',
halted: '0',
type: 'EQ',
bidsize: '2900',
fastmarket: '0',
asksize: '300',
close: '16.64',
timestamp: 'May 18, 2011 3:00 PM EST',
open: '16.64',
productid: 'CSCO:NSDQ:EQ',
bid: '16.63',
exchange: 'NSDQ',
symbol: 'CSCO',
news: '0',
quotetype: '2',
percentchange: '0.0006',
symboldesc: 'CISCO SYS INC COM',
price: '16.65',
utctime: '1305748800',
volume: '92738240',
high: '16.66',
quotestatus: '0',
low: '16.34',
ask: '16.64',
timestring2: '05/18/11 04:00 PM ET'
},
{
timezoneid: 'EST',
change: '0.04',
halted: '0',
type: 'EQ',
bidsize: '91200',
fastmarket: '0',
asksize: '241000',
close: '2.14',
timestamp: 'May 18, 2011 3:00 PM EST',
open: '2.13',
productid: 'SIRI:NSDQ:EQ',
bid: '2.17',
exchange: 'NSDQ',
symbol: 'SIRI',
news: '0',
quotetype: '2',
percentchange: '0.0187',
symboldesc: 'SIRIUS XM RADIO INC COM',
price: '2.18',
utctime: '1305748800',
volume: '74540998',
high: '2.2',
quotestatus: '0',
low: '2.12',
ask: '2.18',
timestring2: '05/18/11 04:00 PM ET'
}
]
}
I want to show some of the values of the response on the site. But I am not able to retrieve the values.
Can someone help.
$.ajax({
type: 'GET',
url: quoteURL,
dataType: 'json',
timeout: 10000,
crossDomain: true,
success: function(result) {
alert(result.descriptor[0].template);
}
});
and if you wanted to loop through all descriptors:
$.each(result.descriptor, function() {
var template = this.template;
var componentname = this.componentname;
// TODO: process the template and componentname
});
or:
alert(result['invest.mostactive'].MoverExchange);
etc... depending on what you want to show
You can use define a global variable in case you want to use the response out the success function scope.
Just use
var cachedResp;//at global scope
$.ajax({
type: 'GET',
url: quoteURL,
dataType: 'json',
timeout: 10000,
crossDomain: true,
success: function(result) {
cachedResp = result; //this is now available out of the function
}
});
Related
Sumo select is not refreshing the data in it.
Action Method is return the correct List.
Just like J QUERY multi select rebuild()
function is available is there anything I am missing?
$("#ddlCountry").change(function () { BindDDlLocation(CountryId); });
function BindDDlLocation(CountryId) {
var ddlLocation = $("#ddlLocation");
$.ajax({
url: RootUrl + '/Home/BindMasterDropDown',
type: "GET",
data: { TableType: 'tbllocation', RegionId: '0', Country_id: CountryId, Categ_Id: '0', SubCateg_Id: '0', EntityID: '0', DepartmentID: '0' },
datatype: 'json',
async: false,
success: function (result) {
$("#ddlLocation").html('');
ddlLocation.append($("<option></option>").val('').html('--select--'));
$.each(result, function (key, value) {
ddlLocation.append($("<option></option>").val(value.ID).html(value.vDescription));
});
//alert("location binded");
$("#ddlLocation").SumoSelect({ csvDispCount: 1, search: true, searchText: 'Enter here.' });
$(".SumoSelect").css('margin-top', '15px');
},
error: function (err) {
alert(err.statusText);
}
});
}
This is the ANSWER: It works fine now.
REFERENCE :
https://github.com/HemantNegi/jquery.sumoselect/issues/286
//bimmy
$("#ddlLocation").SumoSelect({ csvDispCount: 1, search: true, searchText: 'Enter here.', triggerChangeCombined: false });
$("#ddlLocation").SumoSelect().sumo.reload();
$(".SumoSelect").css('margin-top', '15px');
//bimmy
Full CODE:
function BindDDlLocation(CountryId) {
var ddlLocation = $("#ddlLocation");
$.ajax({
url: RootUrl + '/Home/BindMasterDropDown',
type: "GET",
data: { TableType: 'tbllocation', RegionId: '0', Country_id: CountryId, Categ_Id: '0', SubCateg_Id: '0', EntityID: '0', DepartmentID: '0' },
datatype: 'json',
async: false,
success: function (result) {
$("#ddlLocation").html('');
ddlLocation.append($("<option></option>").val('').html('--select--'));
$.each(result, function (key, value) {
ddlLocation.append($("<option></option>").val(value.ID).html(value.vDescription));
});
//bimmy
$("#ddlLocation").SumoSelect({ csvDispCount: 1, search: true, searchText: 'Enter here.', triggerChangeCombined: false });
$("#ddlLocation").SumoSelect().sumo.reload();
$(".SumoSelect").css('margin-top', '15px');
//bimmy
},
error: function (err) {
alert(err.statusText);
}
});
}
$('.the_name_of_select_class').SumoSelect().reload();
I need to bind jquery dataTable using handler and I am sending parameters to that handler which is through object log given below.On button click I am calling the a function in which I have written the below code. On clicking on the button I need to have the datatable.But the problem is that I am unable to bind the jquery datatable. Please help.
Is there anyway to pass log as parameter to jquery datatable call and capture that in handler?
var log = { LogType: logType, InstanceID: instanceId, StartDateTime: StartDateTime, EndDateTime: EndDateTime, UserId: UserId, SearchKey: SearchValue, ProjectID: projectId, ClassID: ClassId, MethodID: MethodId, UserName: UserName, FilePath: FilePath };
$.ajax({
url: "LogManager.ashx",
dataType: "json",
responseType: "json",
data: { searchlog: JSON.stringify(log) },
success: function (data) {
$('#tblLogTable').DataTable({
"data": data,
"columns": [
{ 'data': "stProjectName" },
{ 'data': "stMethodName" },
{ 'data': "stUserName" },
{ 'data': "stFilePath" },
{ 'data': "stClassName" },
{ 'data': "inUserId" },
{ 'data': "dtCreationTime" },
{ 'data': "stLog" },
{ 'data': "stInstance" },
],
"language": {
"emptyTable": "There are no records at present.",
"zeroRecords": "There were no matching records found."
},
processing: true,
serverSide: false,
ordering: true,
paging: true,
searching: true
});
},
error: function (data) {
alert(data);
}
});
It should be the other way around e.g.:
<script type="text/javascript" src="/assets/js/datatables.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$('#mytable').DataTable({
processing: true,
serverSide: true,
ajax: {
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/DataTables.aspx/Data",
data: function (d) {
return JSON.stringify({ parameters: d });
}
}
});
});
</script>
I'm a little bit new with justGage.js and I would like to load some data from MySQL. this is my gage code:
var g3 = new JustGage({
id: "g3",
value: 0,
min: 0,
max: 1000,
title: "Scripts Started Today",
label: "",
levelColors: ['#1ab394'],
levelColorsGradient: false
});
...and the AJAX call is this:
(function updateScripts() {
$.ajax({
type: "GET",
url: '#Url.Action("GetQueryResult")',
context: document.body,
data: {
querySetName: 'dashboard-script-statistics',
queryName: 'NumOfStartedScript'
},
success: function (serveData) {
serveData = JSON.parse(serveData);
if (serveData.Success) {
$("#stat-7-value").html(serveData.Result.NUM_SCRIPT_STARTED_TODAY);
g3.refresh(serveData.Result.NUM_SCRIPT_STARTED_TODAY);
} else {
$("#stat-7-value").prop(serveData.ErrorMessage);
}
},
error: function (xhr) {
$("#stat-7-value").attr('title', 'Error Status: ' + err.status);
},
complete: function () {
setTimeout(updateScripts, 2000);
}
});
})();
It's putting a 0 instead of 3. I checked the data and it's fine. But the value presented is 0.
For some reasons I cannot use MVC-wrapper of Kendo grid. So I am trying to build Kendo grid on JavaScript.
There are 2 main problems when trying to update or create records on grid.
1-)All operations(destroy,update,create) on grid just go to create action by Datasource's of Kendo grid. For example after update a record, datasource send data to this URL to many times(number of columns):
http://localhost:63186/Administrator/DefinitionDetailCreate. It should pass values to:
http://localhost:63186/Administrator/DefinitionDetailUpdate
2-)After operation(update or create) Grid sends all data to Action Method instead of new or updated data. So it sends requests the number of columns on grid
JavaScript:
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
data: {DefinitionCode: code},
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")',
type: "POST",
dataType: "text"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "text",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "text",
}
},
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: {editable: false, nullable: true},
DESCRIPTION: {validation: {required: true}}
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: {style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{command: ["edit", "destroy"], title: "Operasyon", width: "100px"}],
editable: "popup"
});
Controller:
[HttpPost]
public ActionResult DefinitionDetailUpdate(Guid ID,Guid REFERENCEID,string DESCRIPTION)
{
return null;
}
[HttpPost]
public ActionResult DefinitionDetailCreate(Guid ID, Guid REFERENCEID, string DESCRIPTION)
{
return null;
}
First you might need to add parameterMap, this will help identify server side methods:
parameterMap: function (options, operation) {
var out = null;
switch (operation) {
case "create":
out = '{ "param":' + options.somevalue + '}';
break;
case "read":
out = '{ "id":' + options.somevalue + '}';
break;
case "update":
out = '{ "id":' + options.somevalue + '}';
break;
case "destroy":
out = '{ "id": ' + options.somevalue + '}';
break;
}
return out;
}
I would also suggest to keep all the dataTypes as dataType: "json"
Also you seem to be missing contentType in your transports definitions :
update: {
url: _op.serviceBaseUrl + "Update",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
complete: function (jqXhr, textStatus) {
}
},
i have posted answer for the same type of question, you may have a check
or
you may Use this code
js
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
type: "POST",
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")' ,
type: "POST",
dataType: "json"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "json",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "json",
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
} },
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: { editable: false, nullable: true },
DESCRIPTION: { validation: { required: true } }
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: { style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{ command: ["edit", "destroy"], title: "Operasyon", width: "100px" }],
editable: "popup"
});
Controller
[HttpPost]
public ActionResult DefinitionDetailUpdate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
[HttpPost]
public ActionResult DefinitionDetailCreate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
Note that parameterMap: function() send updated data in serialize string format with name models so you should use "models" as parameter name in your action
i hope this will help you:)
I'm having some troubles debugging this and getting a resolution.
My data is being returned to me correctly, but it's throwing out the TypeError at me when I put a break point on the 'loadexception' function. Here is the error:
description - "'prototype' is null or not an object"
message - "'prototype' is null or not an object"
name - "TypeError"
number - -2146823281
So even though my data is coming back right, my callbox message box is always getting thrown on the error.
V2020.dsPricing = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
method: 'POST',
url: url,
headers: {"Content-Type": "application/json; charset=utf-8"},
jsonData: Ext.util.JSON.encode({ serviceId: objPricingReturn.serviceId })
}),
reader: PricingJsonReader()
});
V2020.dsPricing.on('loadexception', function(obj, options, response, err) {
Ext.MessageBox.show({
title: 'Error',
msg: url + ' POST method fail...ErrorCode:' + response.status,
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.ERROR
});
});
V2020.dsPricing.load({
callback: function(records, o, s) {
if (!s) Ext.MessageBox.show({
title: 'Error',
msg: ' Failed to load pricing data',
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.ERROR
});
}
});
Here is the JsonReader code
function PricingJsonReader() {
var pricingReaderObject = new Ext.data.JsonReader({
root: 'GetServicePriceByIdResult.ServicePricing',
fields: [{
name: 'priceId',
type: 'int'
},
{
name: 'serviceId',
type: 'int'
},
{
name: 'price',
type: 'float'
},
{
name: 'startDate',
type: 'date',
dateFormat: 'n/j/Y'
},
{
name: 'endDate',
type: 'date',
dateFormat: 'n/j/Y'
},
{
name: 'updatedBy',
type: 'string'
},
{
name: 'updateDate',
type: 'date',
dateFormat: 'n/j/Y'
}]
})
return pricingReaderObject;
}
The response (I think this is what you are asking for)
{"GetServicePriceByIdResult":{"ServicePricing":[{"priceId":14,"serviceId":1,"price":70.0000,"startDate":"6\/14\/2010 12:00:00 AM","endDate":"12\/31\/2011 12:00:00 AM","updatedBy":null,"updateDate":null},{"priceId":142,"serviceId":1,"price":70.0000,"startDate":"6\/14\/2010 12:00:00 AM","endDate":"12\/31\/2011 12:00:00 AM","updatedBy":null,"updateDate":null}]}}
you're using JsonStore & passing a reader object to it but jsonStore gets config of a JsonReader & creates a reader itself. you have 2 choices:
use Ext.data.Store for V2020.dsPricing
move configs of your JsonReader to JsonStore & don't pass reader to JsonStore anymore
solution 1:
var url = "http://localhost/r.json";
objPricingReturn = {serviceId:10};
function PricingJsonReader() {
var pricingReaderObject = new Ext.data.JsonReader({
root: 'GetServicePriceByIdResult.ServicePricing',
fields: [{
name: 'priceId',
type: 'int'
},
{
name: 'serviceId',
type: 'int'
},
{
name: 'price',
type: 'float'
},
{
name: 'startDate',
type: 'date',
dateFormat: 'n/j/Y'
},
{
name: 'endDate',
type: 'date',
dateFormat: 'n/j/Y'
},
{
name: 'updatedBy',
type: 'string'
},
{
name: 'updateDate',
type: 'date',
dateFormat: 'n/j/Y'
}]
})
return pricingReaderObject;
}
V2020 = {};
V2020.dsPricing = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
method: 'POST',
url: url,
headers: {"Content-Type": "application/json; charset=utf-8"},
jsonData: Ext.util.JSON.encode({ serviceId: objPricingReturn.serviceId })
}),
reader: PricingJsonReader()
});
V2020.dsPricing.on('loadexception', function(obj, options, response, err) {
Ext.MessageBox.show({
title: 'Error',
msg: url + ' POST method fail...ErrorCode:' + response.status,
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.ERROR
});
});
V2020.dsPricing.load({
callback: function(records, o, s) {
if (!s) Ext.MessageBox.show({
title: 'Error',
msg: ' Failed to load pricing data',
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.ERROR
});
}
});