extjs4 data.store use with proxy - ajax

I want to get data from Yii controller action in Ext.data.store with following code:
var vehicles = new Ext.data.Store({
reader: new Ext.data.JsonReader({
fields: ['vehiclename'],
root: 'vehicles'
}),
proxy: new Ext.data.HttpProxy({
url: '<?php echo $this->createUrl('GetVehicles');?>'
}),
autoLoad: true
});
or following code for vehicles:
var vehicles = Ext.create('Ext.data.Store', {
fields: [
{name: 'vehiclename'}
],
proxy: {
type: 'ajax',
url: '<?php echo $this->createUrl('GetVehicles'); ?>',
reader: {
type: 'json',
root:'vehicles'
}
},
autoLoad: true
});
My action code is:
public function actionGetVehicles()
{
$sql = "select vehicleName from vehicletbl inner join companytbl on vehicletbl.companyid=companytbl.companyid and companytbl.companyid='2';";
$vehicles = Yii::app()->db->createCommand($sql)->queryAll();
//var_dump($vehicles);
echo '{vehicles:'.json_encode($vehicles).'}';
}
When i send request to action with browser address bar i get following json:
{vehicles:[{"vehiclename":"pride"},{"vehiclename":"benz"}]}
but i don't know why Ext.data.store can't get data and store themes!
What is wrong in my code?
I use store at:
items: [treePanel,Ext.create('Ext.grid.PropertyGrid', {
title: 'History',
closable: false,
header: true,
sortableColumns: false,
customEditors: {
Vehicle: Ext.create('Ext.form.ComboBox', {
store: vehicles,
queryMode: 'local',
displayField: 'vehiclename'
})
},
/*propertyNames: {
'evtStart': 'Start Time'
},*/
source: {
"Vehicle": 'Select Vehicle',
"Select Start Date": false,
"Select End Date": true
}
})]
Chrome developer tool output:

You returned json is not valid. It should be:
{"vehicles":[{"vehiclename":"pride"},{"vehiclename":"benz"}]}
(Quotation marks around the root vehicles).

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(),

Server side paging with JqxGrid and Codeigniter

I was trying to implement server side paging with JqxGrid and Codeigniter. I am following the tutorial here, http://www.jqwidgets.com/server-side-paging-with-jquery-grid/. I have a problem with posting pagenum and pagesize to Codeigniter controller. When I tried $this->input->get('') method, its not working.
Here is my Source for jqxgrid,
var source =
{
datatype: "json",
datafields: [
{ name: 'itemname'},
{ name: 'category'},
],
id: 'id',
url: '<?php echo base_url()."index.php/cart/reportgriddata/"; ?>',
root: 'Rows',
beforeprocessing: function(data)
{
source.totalrecords = data[0].TotalRows;
}
};
And in my controller, I used following method to get parameters from get-url of dataadapter
$pagenum =$this->input->get('pagenum');
$pagesize =$this->input->get('pagesize');
But here the values getting for both $pagenum and $pagesize is null.
Got it working by using POST method.
var source =
{
type:"POST"
datatype: "json",
datafields: [
{ name: 'itemname'},
{ name: 'category'},
],
id: 'id',
url: '<?php echo base_url()."index.php/cart/reportgriddata/"; ?>',
root: 'Rows',
beforeprocessing: function(data)
{
source.totalrecords = data[0].TotalRows;
}
};
and using,
$pagenum =$this->input->post('pagenum');
$pagesize =$this->input->post('pagesize');

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.

sencha touch ajax load list

Here is my code
I want to load some data by Jsonp and display as list items.
Ext.setup({
onReady: function(){
Ext.regModel('Provinces', {
fields: [{
name: 'ProvinceID',
type: 'int'
}, {
name: 'ProvinceName',
type: 'string'
}]
});
var store = new Ext.data.Store({
autoLoad: true,
model: 'Provinces',
fields:['ProvinceName', 'ProvinceID'],
proxy: {
url: 'http://172.19.44.122/BC/Home/GetProvices',
type: 'jsonp'
},
autoLoad:true
});
new Ext.List({
fullscreen: true,
itemSelector: '.province',
tpl: '<tpl for="."><div class="province">{ProvinceName} - {ProvinceID}</div></tpl>',
store: store
});
}
});
The JSONP data looks like this:
Ext.data.JsonP.callback1([{"ProvinceID":1,"ProvinceName":"shanghai"},"ProvinceID":2,"ProvinceName":"zhejiang"}]);
but the reslut is the page only display two empty lines .
You should use the itemTpl property on the list, instead of tpl, like this:
new Ext.List({
fullscreen: true,
itemTpl: '{ProvinceName} - {ProvinceID}',
store: store
});

I'm having trouble with ExtJS4 passing a querystring (parameter) with store.load

I'm having trouble passing parameters into the GetAll method of my controller. I tried Filter as below but no luck. any suggestions?
Ext.define('AM.store.Sessions', {
extend: 'Ext.data.Store',
model: 'AM.model.Session',
autoLoad: false,
proxy: {
type: 'ajax',
api: {
read: 'Session/GetAll',
update: 'data/updateUsers.json'
},
reader: {
type: 'json',
root: 'Data',
successProperty: 'success'
},
filters: [
new Ext.util.Filter({
property: 'eyeColor',
value: 'brown'
})
]
}
});
Im not sure what you are after. But stating extraParams in you proxy will put that parameter on every load() on your store. Like this.
Ext.define('AM.store.Sessions', {
extend: 'Ext.data.Store',
model: 'AM.model.Session',
autoLoad: false,
proxy: {
type: 'ajax',
api: {
read: 'Session/GetAll',
update: 'data/updateUsers.json'
},
extraParams:{
eyeColor:'brown'
}
reader: {
type: 'json',
root: 'Data',
successProperty: 'success'
}
}
});
You could also listen on the "beforeLoad" event on the store and modifu parameters there.
OR.. you could just pass parameters to the load() function as this
var myStore = Ext.create('AM.store.Session');
myStore.load({
params:{
eyeColor:'brown'
}
})

Resources