how to post array by store of sencha - arrays

I create one store and init it with some params with one array.when I execute the load function, the array parameter becomes a string '[object object]'
the code as follows:
store:
Ext.define('test.store.info',{
extend: 'Ext.data.Store',
config:{
model:'test.model.info',
proxy:{
type:'ajax',
url:'http://domain/path',
actionMethods:'POST'
}
}
});
model:
Ext.define('test.model.info',{
extend:'Ext.data.Model',
config:{
fields:[
'code',
'data'
]
}
})
use in controller:
var store = Ext.getStore('info');
params = {
t1:[{
f1:'aa'
},{
f2:'bb'
}],
t2:'ddd'
}
console.log(params)
store.load({
params:params
});
or I just use Ajax function instead load function , the result is the same.
Ext.Ajax.request({
url:'http://domain/path',
method:'post',
params:params,
});
I check the xhr within network of browser , it is a string as follows:
t1:[object Object]
t1:[object Object]
t2:ddd
when I check the server log, it shows :
t1:'[object Object]'
t1:'[object Object]'
t2:'ddd'

I found the solution , thank you
1, just use jsonData instead params during Ajax, like follows:
Ext.Ajax.request({
url: ajmd.util.version.getHost()+'/archimedes/update/selfInfo',
method:'post',
// params:params,
jsonData:params
});
2, or just encode the data before send
params.t1 = Ext.encode(params.t1);

If you name the parameter "foo[]", then it will encode it as a POST array making it easy to consume on the server side. Note the [] at the end.
var companies = [1,2,3];
Ext.Ajax.request({
url: '...',
method: "post",
params: {
'companies[]': companies,
},
success: function (response) {
console.log("done");
}
});

Related

How to send form data from Angularjs to Django

I did the application on the sample from this lesson. Here, using DRF, a list of all added games is displayed on the page. I would really like to learn how to write a simple form of adding a new record to the database (two fields: title and description [as in the example]).
With js, I'm not very familiar with so far, so I do not know which side to get close to solving the problem.
$scope.saveUser = function(event) {
postForm({ id: 0 }, $('#FormName'), $scope, function(data) {
})
}
function postForm(postInfo, form, $scope, callback,) {
var postData = new FormData(form.get(0));
$.each(postInfo, function(key, value) {
postData.append(key, value);
});
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: postData,
cache: false,
dataType: 'json',
processData: false,
contentType: false,
headers: {
"X-CSRFToken": app.getStorage("csrftoken")
},
beforeSend: function() {
$('#loading-image').show();
},
complete: function() {
$('#loading-image').hide();
if(typeof saveButtonId !== typeof undefined) {
$('#'+saveButtonId).removeAttr('disabled');
}
},
success: function(data) {
},
error: function(data) {
//
}
});
};
you'd be updating code in your mysite/backend folder to have some incoming route to insert data into django db using some serializer
sorry I don't have more specific details, but just wanted to convey the general idea
Here's some more information on Django serializers: http://www.django-rest-framework.org/api-guide/serializers/
another tutorial on adding an additional route to django could help

Posting to a REST interface

need to define the name as ID in the URL and need to post an object containing data.
$scope.dvModel.naam is the name that acts as the ID.
filteredObject is the object containing the data, obviously.
This is how I call the service, seems ok according to some examples.
saveDVservice.query($scope.dvModel.naam, filteredObject);
This is the actual service.
.factory('saveDVservice', ['$resource', 'CONSTANTS', function($resource, CONSTANTS) {
'use strict';
return $resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
}]);
This is what I see in my network tab at Query String Parameters:
0:A
1:D
10:n
11:h
12:i
13:l
14:f
15:e
2:A
3:C
4:
5:P
6:a
7:n
8:n
9:e
Which is the name, but looks like an array.
Request Payload contains the actual object in correct order.
Can one give me some guidance on how to handle this?
As I understand, you want to put $scope.dvModel.naam into URL and you want filteredObject to be a request payload. Then you need an object that contains everything that's in filteredObject and additionaly under the key name a value equal to $scope.dvModel.naam.
Also, the definition of your resource probably should change - in second argument $resource requires you to tell it the way of extracting URL data from given object:
$resource(CONSTANTS.REST_BASE_URL + '/dv/:name', {name: '#name'}, { query: { method: 'POST', isArray: false, headers: { 'Content-Type': 'application/json' }}});
Unfortunately, $resource isn't the best $http wrapper to use when your payload data is separated from URL data. Maybe it would be better to wrap the filteredObject data in payload in some other object? Then your $resource object would be much nicer, like {name: ..., data: {"0": "A", "1": "D", ...}}
Since default action for query is {method: 'GET', isArray: true}, I'd leave that be and use another default, save instead. That should work out-of-the-box.
app.factory('DVService', function ($resource) {
return $resource(CONSTANTS.REST_BASE_URL + '/dv', {name: '#name'}, {});
});
.
app.controller('MainCtrl', function ($scope, DVService) {
var postData = {
name: 'name',
fooProp: 'foo',
barProp: 'bar'
};
// save/post
DVservice.save({dv: postData}).$promise.then(function (response) {
console.log(response);
});
//query/get
DVService.query({name: 'name'}).$promise.then(function (response) {
console.log(response);
});
});

How do I retrieve all data from jsonstore in sencha

Morning,
I have created a store in my controller like this:
var storeCompanies = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
type: 'GET',
url: url+'dashboard?Uid='+uid+'&Ude='+ude,
reader: {
type: 'json',
root: 'root',
totalProperty: 'total'
},
headers: {
'Accept' : 'application/json;application/x-www-form-urlencoded',
'Content-Type' : 'application/x-www-form-urlencoded',
},
}),
root: 'd',
type: 'localstorage',
autoLoad : true,
id: 'company_Id',
scope : this,
fields: ['Name']
});
console.log(storeCompanies);
The console log shows that the store is being created and populated properly. I need to retrieve all the values for a dropdown.
I tried this but it returned undefined.
All other info I have found seems to instruct on how to find just one value.
What's the easiest and most effecient way to retrieve all the data?
storeCompanies.on('load', function() {
console.log(storeCompanies.data); //<--- data is a Ext.util.MixedCollection
});
If you need to retrieve all the values in the JSonStore you could use each(). Here's an example: http://docs.sencha.com/touch/2.2.1/#!/api/Ext.data.JsonStore-method-each
Thanks to #Vlad for his input. Here is what I settled on:
storeCompanies.on('load', function() {
numcomps = storeCompanies.data.items.length; //get number of elements in store
for(var ic = 0;ic<numcomps;ic++){
console.log(storeCompanies.data.items[ic].raw);
}
});

Model without a Store

I created a model which contains a proxy to load a single record and its takes no params. I don't want to use a store since I'll never have more then one record. I create an instance of the Model but can't figure out how to tell it to call and load the record from the server. This is the only example I could find, but I don't have an id to pass.
User.load(123, {
success: function(user) {
console.log("Loaded user 123: " + user.get('name'));
}
});
Also I'm making and ajax call and not a rest call in case that matters.
The load(id, [config]) is static and will return provide you with a new record instance. It uses the proxy that was set via setProxy(proxy) (also static). Per default it will send a read request with the params id: 123. The static method allows you to set some default callbacks within the optional config object. These callbacks are needed to get the instance of the loaded record (or the error).
How it works
// create a Model class
Ext.define('MyApp.User', {
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'}
]
});
// apply a proxy instance
MyApp.User.setProxy(/*YourAjaxProxy*/);
// prepare a handler
var cb = function(model, op) {
// log the new model instance
console.log(model);
};
// get a instance
MyApp.User.load(123, {
scope: this, // should be the scope of the callback (cb)
success: cb
});
Not what you need? Just comment...
Just make an Ajax request and store the result in a variable.
Ext.Ajax.request({
url: '/data/get',
method: 'GET',
params: {
requestID: 'XXXX',
connName: 'yyyy'
},
success: function (responseData) {
var countResult = Ext.decode(responseData.responseText); }
});

How to pass parameter to Ext.data.Store?

I am using following code:
var genres1 = new Ext.data.Store({
reader: new Ext.data.JsonReader({
fields: ['pincode','place_name'],
root: 'rows'
}),
proxy: new Ext.data.HttpProxy({
url: 'pointalong.php',
method: 'GET'
})
});
but i want to pass 3 parameters to my php file. how should i proccess? and also how would i get at php file.
There are two possibilities. The first one is to use store baseParams config:
var genres1 = new Ext.data.Store({
baseParams: {
param1: 'value1',
param2: 'value2'
},
// ...
The second one is to send them when you are using load method:
genres1.load({params: {param2: 'anotherValue'}});
Note: params will override any baseParams of the same name
So if you setup store with baseParams like in example above and then use load with params the store will request ...?param1=value1&param2=anotherValue.
... and also how would i get at php file
As usual variable passed via the URL parameters - using $_GET:
$param1 = $_GET['param1'];
I use this and it works perfectly
Ext.define('store.odon.DiagnosticoStore', {
extend : 'Ext.data.Store',
model : 'model.odont.DiagnosticoModel',
proxy: {
type: 'ajax',
api: {
create: CONTEXT_PATH + '/mvc/odona/crear',
read: CONTEXT_PATH + '/mvc/odon/lista',
update: CONTEXT_PATH + '/mvc/odon/update',
destroy: CONTEXT_PATH + '/mvc/odon/delete'
},
reader: {
type: 'json',
root: 'diagnosticos',
successProperty: 'success'
},
writer: {
type: 'json',
writeAllFields: true,
encode: true,
root: 'diagnosticos'
}
}
});
the parameter is assigned to load the store
var storeDiagnostico= getStore(); // Ext.create('store.odon.DiagnosticoStore');
storeDiagnostico.getProxy().setExtraParam("idOdontologia", value);
storeDiagnostico.load();
If the value of the parameter may change (for example, if it comes from another form field), then the most reliable way is to apply the proxy parameter before the load event each time the store loads, as follows:
Ext.create('Ext.data.Store', {
...
listeners:{
beforeload: function(store){
var filterText = Ext.getCmp('filterText').value;
store.getProxy().setExtraParam("filterText", filterText);
}
},

Resources