retrieve data for grid/chart from httpwebrequest call to url - ajax

I am trying to get a grid filled with the json response I would receive when making a httpwebrequest call to a url endpoint which requires authentication. The data will be in json form:
{
"data": [
{
"value": "(\"Samsung Health\")",
"tag": "ME"
},
{
"value": "(\"Samsung Galaxy Tab\")",
"tag": "HIM"
},
{
"value": "(\"Amazon fire\")",
"tag": "ME"
}
]
}
I am not sure how to even start and whether to use Ext.Ajax.Request or some type of call from code behind. I am using vb.net in code behind. Any suggestions appreciated. Sample code for ajax call;
function getMembers() {
var parameters = {
node: dynamicNodeId
}
Ext.Ajax.Request({
url: 'https://data.json',
method: 'GET',
jsonData: Ext.encode(parameters),
success: function (response, opts) {
alert('I WORKED!');
//decode json string
var responseData = Ext.decode(response.responseText);
//Load store from here
memberStore.loadData(responseData);
},
failure: function (response, opts) {
alert('I DID NOT WORK!');
}
});
}
The grid formation:
var grid = Ext.create('Ext.grid.Panel', {
store: store,
stateful: true,
stateId: 'stateGrid',
columns: [
{
text: 'Query',
flex: 1,
sortable: false,
dataIndex: 'query'
},
{
text: 'Last Updated',
width: 85,
sortable: true,
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
dataIndex: 'lastChange'
},
Here query would be the value from the json response and lastChange the current datetime. I tried the proxy request call and realized that since I am calling an endpoint on a different domain I needed to use jsonp.
var myStore = Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'jsonp',
extraParams: {
login: 'username',
password: 'password'
},
url: 'https://api.data/rules.json',
reader: {
type: 'json',
root: 'rules'
},
callbackParam: 'callback'
},
autoLoad: true
});
I might have to just figure out some other way to do by making sure all the data I needed is called to a database by some other function.

The best approach for your situation would be to create store that is configured with a remote proxy. See the example at the top of this documentation page: http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.data.Store
The remote proxy will take care of the AJAX request to retrieve the data, and the store will automatically manage casting the data results to Ext.data.Model instances. Once the store is loaded with data, the grid to which the store is bound will also automatically handle rendering the data that has been populated into the store.

Related

How to remove previous data when executing AJAX request multiple times

I have an issue with ajax calling. It works correct except one thing, when I try to get data with the same option more than one times returns the new response but also still return the data of the previous response.
I think that there is something that I've missed.
ajax script
$('#search').on('click', function () {
var date = $("#date").val();
$.ajax({
type: 'GET',
url: '{{Route("dashboard.status")}}',
data: {
date: date
},
dataType: "JSon",
success: function(response){
console.log(response.manager_hourlog);
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: response.manager_projects,
datasets:
[{
label: response.users,
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
data: response.totals
},]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Project Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
},
error: function(xhr){
console.log(xhr.responseText);
}});
});
});
</script>
You should change your method to POST for json request/response API, will be more secure and avoid laravel cache view it.
type: 'POST',
Try to change method to POST (do same for your api server and route).
If not work, please show your laravel API code.
you should set cache property to false or append "_={timestamp}" to the GET parameter
so add cache to your request:
cache:false
or append timestamp to your url:
url: '{{Route("dashboard.status")}}'+'_='+ + new Date().getTime(),

Ext JS: Load single database entry into model

I'm trying to create a model with a single database entry, instead of creating a store for just one row... doesn't make sense. Anyway, I can create the model by using the static load method, but the URL for my model's proxy is dynamic, so that's not an option, as I want to just load on the fly. Also, creating an instance of the model doesn't seem to work because I can't use the load method, due to it being static...
I've started experimenting with an Ajax call to grab the data, and then loading it into an instance of the model, but the association relationships seem to not get created, even though the plain field values do. This is what I'm attempting to do:
Code
// SectionsModel
Ext.define('SectionsModel', {
extend: 'Ext.data.Model',
fields: ['name']
});
// MY_MODEL
Ext.define('MY_MODEL', {
extend: 'Ext.data.Model',
fields: ['name', 'id'],
hasMany: [{
associationKey: 'sections', name: 'getSections', model: 'SectionsModel'
}],
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'configuration'
}
}
});
var url = 'my/url';
Ext.Ajax.request({
url: url,
method: 'GET',
scope: this,
success: function(res) {
var configObj = Ext.decode(res.responseText);
var configModel = Ext.create('MY_MODEL', configObj);
console.log(configModel);
},
failure: function(res) {
console.error('failed');
}
});
Response
{
"code": 200,
"configuration": {
"name": "TestConfiguration",
"id": 1,
"sections": [{
"name": "section1"
}, {
"name": "section2"
}]
}
}
The above code is dummy code that I wrote for this example... think of it as pseudocode if it doesn't work. Like I said, it does work when I use the static load method, and I can successfully make the Ajax call... the issue is how to create a model with the given data. Would I need to pass in config to the model's constructor, and set the model's proxy's data to the passed in config? Is that proper protocol? I'm just trying to figure out the best approach here. Thanks!
Cross-posted from the Sencha forums.
I have come up with a solution, thanks to one of Mitchell Simoens' blog post. I changed MY_MODEL to look like this:
Ext.define('MY_MODEL', {
extend: 'Ext.data.Model',
fields: ['name', 'id'],
hasMany: [{
associationKey: 'sections', name: 'getSections', model: 'SectionsModel'
}],
constructor: function(data) {
this.callParent([data]);
var proxy = this.getProxy();
if (proxy) {
var reader = proxy.getReader();
if (reader) {
// this function is crucial... otherwise, the associations are not populated
reader.readAssociated(this, data);
}
}
},
proxy: {
type: 'memory',
reader: {
type: 'json'
}
}
});
// in the success of the Ajax call
success: function(res) {
var configObj = Ext.decode(res.responseText);
var configModel = Ext.create('MY_MODEL', configObj.configuration);
console.log(configModel);
}

Kendo Grid calls 'create' operation instead of 'update' after adding new record

I've setup a basic Kendo Grid and I'm using the DataSourceResult class from the PHP Wrapper library on the sever side.
I've come across a strange issue... if I create a new record and then edit it (without refreshing the page), the create operation is called again, rather than the update operation.
If the page is refreshed after adding the new record, the update operation is called correctly after making changes to the record.
I can confirm that the DataSourceResult class is returning the correct data after the create operation, including the id of the new record.
Any ideas why this is happening (and how to stop it)?
Thanks
Update: Here's the datasource code. The query string in the url is just to easily distinguish the requests in Chrome's console. The additional data passed with each request is used by ajax.php to distinguish the different actions requested.
data = new kendo.data.DataSource({
transport: {
create: {
url: '/ajax.php?r=gridCreate',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'create' }
},
read: {
url: '/ajax.php?request=gridRead',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'read' }
},
update: {
url: '/ajax.php?r=gridUpdate',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'update' }
},
destroy: {
url: '/ajax.php?r=gridDestroy',
dataType: 'json',
type: 'post',
data: { request: 'grid', type: 'destroy' }
},
parameterMap: function(data, operation) {
if (operation != "read"){
data.expires = moment(data.expires).format('YYYY-MM-DD HH:mm');
}
return data;
}
},
schema: {
data: 'data',
total: 'total',
model: {
id: 'id',
fields: {
id: { editable: false, nullable: true },
code: { type: 'string' },
expires: { type: 'date' },
enabled: { type: 'boolean', defaultValue: true }
}
}
},
pageSize: 30,
serverPaging: true,
serverSorting: true,
serverFiltering: true
});
Best solution
Set to update, create or delete different Call Action
From Telerik Support :
I already replied to your question in the support thread that you
submitted on the same subject. For convenience I will paste my reply
on the forum as well.
This problem occurs because your model does not have an ID. The model
ID is essential for editing functionality and should not be ommited -
each dataSource records should have unique ID, records with empty ID
field are considered as new and are submitted through the "create"
transport.
schema: {
model: {
//id? model must have an unique ID field
fields: {
FirstName: { editable: false},
DOB: { type: "date"},
Created: {type: "date" },
Updated: {type: "date" },
}
} },
For more information on the subject, please check the following
resources:
http://docs.kendoui.com/api/framework/model#methods-Model.define
http://www.kendoui.com/forums/ui/grid/request-for-support-on-editable-grid.aspx#228oGIheFkGD4v0SkV8Fzw
MasterLink
I hope this information will help
I have also the same problem & I have tried this & it will work.
.Events(events => events.RequestEnd("onRequestEnd"))
And in this function use belowe:
function onRequestEnd(e) {
var tmp = e.type;
if (tmp == "create") {
//RequestEnd event handler code
alert("Created succesully");
var dataSource = this;
dataSource.read();
}
else if (tmp == "update") {
alert("Updated succesully");
}
}
Try to Use this code in onRequestEnd event of grid
var dataSource = this;
dataSource.read();
Hope that it will help you.
Pass the auto-incremented id of the table when you call the get_data() method to display data into kendo grid, so that when you click on the delete button then Deledata() will call definitely.
Another variation, in my case, I had specified a defaultValue on my key field:
schema: $.extend(true, {}, kendo.data.transports["aspnetmvc-ajax"], {
data: "Data",
total: "Total",
errors: "Errors",
model: kendo.data.Model.define({
id: "AchScheduleID",
fields: {
AchScheduleID: { type: "number", editable: true, defaultValue: 2 },
LineOfBusinessID: { type: "number", editable: true },
Not sure what I was thinking but it caused the same symptom.

SharePoint 2013 and Kendo Grid cross domain call issues

I am having a small issue that I just can't seem to figure out. I am trying to make a simple SharePoint 2013 demo app that gets a few fields from a list on the parent site and binds to a kendo grid.
Due to the new nature of SP2013, app's get created in their own local site which makes these calls cross domain. When I make the call, no data is pulled back. When I compare a working call vs the call being made by the app, I can see that a cookie is not present in the call that is failing (which is why no data is being pulled back). If anyone could offer any hints or suggestions on things to try, I would appreciate it.
The List I am trying to call is called KendoGridList and I am trying to pull back the first and last name and bind to the grid. Below is my code:
EDIT: After looking into the code a little deeper, it looks like a cookie is not getting passed in the call to the service. If I take the cookie from a normal rest call to the service which works and add it to the composer in fiddler the call goes through and returns data.
$(document).ready(function () {
$("#grid").empty();
var siteUrl = "site url placed here";
var url = siteUrl + "/_vti_bin/Listdata.svc/KendoGridList/?$select=FirstName,LastName";
grid = $("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: {
url: url,
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json;odata=verbose");
}
}
},
schema: {
type: "json",
model: {
fields: {
FirstName: "FirstName",
LastName: "LastName"
}
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true,
change: function (e) { // data load completed for grid
},
},
filterable: false,
sortable: true,
pageable: true,
scrollable: false,
//groupable: true,
columns: [{
field: "FirstName",
title: "First Name",
width: 50
}, {
field: "LastName",
title: "Last Name",
width: 50
}
]
});
});
I've also tried using:
read: {
url: url,
type: "GET",
dataType: "json",
contentType: "application/json;odata=verbose",
headers: {
"accept": "application/json;odata=verbose"
}
},
If you are using a provider-hosted app you should try using the SP cross-domain library. I think your best bet is to retrieve the data using the library and then bind the resulting info to the grid.
http://blogs.msdn.com/b/officeapps/archive/2012/11/29/solving-cross-domain-problems-in-apps-for-sharepoint.aspx

Kendo UI does not call create if a function is specified

Using Kendo.web.js versions 2013.2.716 and 2012.3.1315, I am trying to use a function in my transport.create rather than calling a URL. What I find is that the function does not get called. Instead a default URL is called and the resulting HTML appears to cause an error in the bowels of kendo because it is expected to be JSON instead.
I assume that this is some type of configuration error, but I can't figure out where the problem is.
Here is a snippet of the code:
var clientListDS = new kendo.data.DataSource({
transport: {
read: {
url: window.baseUrl + 'HealthCheck/ClientSummary',
dataType: 'json',
type: 'POST'
},
create: function(a,b,c) { alert('Create'); },
createY: window.baseUrl + 'HealthCheck/DontCallMe',
createX: {
url: window.baseUrl + 'HealthCheck/DontCallMe',
dataType: 'json',
type: 'POST'
},
whatWeWantCreateToDo: function () {
showChooseDialog('Some Random String', 'Select Client', OnRefreshInactiveClientList);
},
destroy: function () {
alert('destroy');
},
update: function () {
alert('update');
}
},
autoSync: true,
schema: {
model: {
id: 'ID',
fields: {
ID: { required: false, type: 'number', nullable: true },
ClientName: { type: 'string' },
ClientTag: { type: 'string' },
Status: { type: 'string' }
}
}
}
});
Then I use the resulting data source to build a grid like this:
$('#cClientGrid').kendoGrid({
dataSource: clientListDS,
columns: [
{ field: 'ClientTag', title: 'Tag'},
{ field: 'ClientName', title: 'Name' },
{ field: 'Status' }
],
editable: {
mode: 'incell',
createAt: 'bottom'
},
edit: function (pEvent) {
if (pEvent.model.isNew())
alert('create');
else
alert('Edit');
},
toolbar: ['create']
});
Some behavior that is worthy of note:
You see several attempts at the create configuration. If I use CreateY or CreateX, it will call the resulting URL. If I use Create or WhatWeWantCreateToDo, I end up downloading the containing page with each element of my schema as get string items (I assume this is some type of default behavior as I can't find a reference to the URL which is downloaded).
When I turn off autoSync, the grid will call its edit function when I use the toolbar to create a new item. When I turn on autoSync, the edit function does not get called. Instead the data source create functionality runs.
Any thoughts or insight on how I might be able to call a function instead of a URL will be appreciated.
First make in transport everything being an URL or a function, do not mix them up.
If you need to implement read as a function, you simply do:
transport: {
read : function (options) {
$.ajax({
url: window.baseUrl + 'HealthCheck/ClientSummary',
dataType: 'json',
type: 'POST',
success : function (result) {
options.success(result);
}
});
},

Resources