I have read all the posts on Stackoverflow regarding this issue and tried the following:
1) Adding $.param({}) wrapper
messages.fetch({
data: $.param({ limit: 14 }),
});
2)
Setting traditional to true
messages.fetch({
data: { limit: 14 },
traditional: true
});
3)
Setting processData to true
messages.fetch({
data: { limit: 14 },
processData: true,
});
Despite this, none of these methods work. Is there something I am missing here?
For what I think you're tying to do, you need to use the "url" property on the model/collection. Fetch is a GET type, not a PUT or POST so you aren't sending "data" to the server. Try something like the following:
Note that $.param({ limit: 14 }) returns "limit=14" The point is, that is not a valid serialized object that the server is going to understand.
If your "fetch" method is a "HttpGet"
var MyModel = Backbone.Model.extend({
// place holder for models api. Also look at: http://backbonejs.org/#Model-urlRoot
_baseUrl = 'api/somewhere/great'
// see: http://backbonejs.org/#Model-url
url: function() {
// this returns 'api/somewhere/great?limit=14';
return this._baseUrl + '?' + $.param({ limit: 14 });
}
});
Now, if you want to HttpPut or HttpPost, then you can override "fetch" and do something like the following:
var MyModel = Backbone.Model.extend({
url = 'api/somewhere/great'
fetch: function(options) {
options = options || {
data: {
limit: 14
}
};
/*
signature method of sync: Backbone.sync = function (method, model, options)
*/
return this.sync("create", this, options);
}
});
References:
http://backbonejs.org/#Model-url
http://api.jquery.com/jQuery.param/
Related
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
I am creating a dynamic grid (should be paginated) using the data from a POST rest request to server (code below). I am passing the pageid and pagesize to the server during the first request (on load) and it responds back with the appropriate data. I have docked a paging toolbar to grid and now I want to enable pagination on click of next, last etc of the pager. How do I POST a request to server and get back the appropriate data back to reconfigure the grid with the next page's data?
var screenResults = {};
screenResults.pageid =1;
screenResults.pagesize = 10;
screenResults = Ext.JSON.encode(screenResults);
Ext.Ajax.request({
url : 'http://localhost/service/getGridData',
method : 'POST',
timeout: 5000000,
scope: this,
dataType: 'json',
jsonData: screenResults,
success: function(response){
var grid = Ext.getCmp("idSearchResultsGrid");
var gridData = Ext.decode(response.responseText);
var fields = gridData.data.fields;
var newColumns = gridData.data.columns;
var arr = gridData.data.data;
var data = [];
for(var i=0;i<arr.length;i++){
var obj = arr[i].resultsMap;
data.push(obj);
}
var newStore = Ext.create('Ext.data.Store', {
storeId: 'DynamicGridStore',
pageSize:10,
fields: fields,
data: data
/*
proxy: {
type: 'ajax',
url : 'http://localhost/service/getGridData',
method : 'POST',
timeout: 5000000,
jsonData: screenResults,
actionMethods: {
read : 'POST'
}
}
*/
});
//debugger;
/*
globalStore = newStore.load({
params: {
start: 0,
limit: 10
}
});
*/
var pagingBar = Ext.create('Ext.PagingToolbar', {
pageSize: 10,
store: newStore,
dock: 'bottom',
displayInfo: true
});
grid.removeDocked(grid.getDockedItems()[1]);
grid.addDocked(pagingBar);
grid.reconfigure(newStore, newColumns);
},
failure: function(response){
console.log(response);
}
});
},
First of all, you don't need to explicitly do AJAX calls like that. They will be done for you behind the scenes by the store's proxy — provided that the proxy is properly configured (yours is commented out at the moment).
Your task is very trivial and covered by multiple examples. Have a look at this one. Click on Details on the right hand side to see the code.
Also see Ext.toolbar.Paging documentation.
I'm pretty new to backbone and how it works and inherited a bunch of code but I can't solve this at all:
I have a user model:
var User = Backbone.Model.extend({
idAttribute: 'username',
defaults: {
username: "",
email: "",
roles : [],
password: ""
}
});
var Users = Backbone.Collection.extend({
model: User,
initialize: function(args, options) {
if (options && options.dialog) {
this.dialog = options.dialog;
}
},
parse: function(response) {
if (this.dialog) {
this.dialog.populate(response);
}
return response;
},
url: function() {
var segment = AdminUrl + "/users";
return segment;
}
});
Then elsewhere in my view I'm doing:
user.save({username: $newtarget.val()},null);
or
user.save();
The PUT is fired to the correct url but every time its triggered it sends the data
Content-Type application/x-www-form-urlencoded; charset=UTF-8
but my Jersey endpoint accepts application/json
Everywhere I read people are struggling to put urlencoded data but my problem is the otherway around!
Parameters are being send as url params:
username=admin&email=&password=admin&roles%5B%5D=ROLE_USER&roles%5B%5D=ROLE_ADMIN&id=1
===EDIT===
If I force the content type and data:
user.save({}, {data: JSON.stringify(user.attributes),contentType: "application/json"});
The put works fine, which is bizarre.
Backbone.emulateJSON = false;
is true for some reason
From the docs
Turn on emulateJSON to support legacy servers that can’t deal with
direct application/json requests … will encode the body as
application/x-www-form-urlencoded instead and will send the model in a
form param named model.
http://backbonejs.org/docs/backbone.html
In my code I have:
var EntityResource = $resource('/api/:entityType', {}, {
postEntity: { url: '/api/:entityType/', method: 'POST' },
getEntity: { url: '/api/:entityType/:entityId', method: 'GET' },
putEntity: { url: '/api/:entityType/:entityId', method: 'PUT' },
deleteEntity: { url: '/api/:entityType/:entityId', method: "DELETE" },
getEntities: { url: '/api/:entityType/:action/:id', method: 'GET', isArray: true },
});
Then I am using the following to get data:
getProjects: function (
entityType,
deptId) {
var deferred = $q.defer();
EntityResource.getEntities({
action: "GetProjects",
entityType: entityType,
deptId: deptId
},
function (resp) {
deferred.resolve(resp);
}
);
return deferred.promise;
},
and the following to call getProjects:
entityService.getProjects(
'Project',
$scope.option.selectedDept)
.then(function (result) {
$scope.grid.data = result;
}, function (result) {
$scope.grid.data = null;
});
I think the intermediate function getProjects is not needed and I would like to directly use $resource.
Can someone give me some advice on how I could do this? I looked at the AngularJS documentation for $resource and it's not very clear for me.
$resource calls by default return empty arrays and then fill them up when the response is received. As mentioned in documentation
It is important to realize that invoking a $resource object method
immediately returns an empty reference (object or array depending on
isArray). Once the data is returned from the server the existing
reference is populated with the actual data.
There are default 5 methods already defined on resource, get,save,query,remove,delete. You can directly call these rather than defining your own as you have done like postEntity, but the url template remains the same.
So once you define resource like this
var entityResource = $resource('/api/:entityType');
you can make calls like
var entity=entityResource.get({entityType:1},function(data) {
//The entity would be filled now
});
See the User example in documentation
If you want to return promise then you have to wrap the calls into your your service calls like you did for getProjects.
Update: Based on your comment, the definition could be
var entityResource = $resource('/api/:entityType/:action/:id')
Now if you do
entityResource.get({},function(){}) // The query is to /api
entityResource.get({entityType:'et'},function(){}) // The query is to /api/et
entityResource.get({entityType:'et',:action:'a'},function(){}) // The query is to /api/et/a
entityResource.get({entityType:'et',:action:'a',id:1},function(){}) // The query is to /api/et/a/1
Hope it helps.
$resource does expose $promise but it is on return values and subsequent calls.
I'm working out my first backbone.js app and have run into a bit of a wall. Perhaps someone can help me past this hurdle (gap in my understanding). What I want/need to do is to return the collection data to my router, so I can bind it to a Kendo UI Grid, but I'm not seeing any of the search results in my collection... I figure I must be missing something fundamental, but I'm not sure what it is.
Here is what I have so far:
ES.Router = Backbone.Router.extend({routes: {
'': 'search',
'search': 'search',
'results': 'results'
},
results: function() {
var resultsData = new ES.Results();
var boo = resultsData.fetch({
data: JSON.stringify({"query":"myquery"}),
type: 'POST',
contentType: 'application/json'
});
console.log(boo);
}});
ES.Result = Backbone.Model.extend();
ES.Results = Backbone.Collection.extend({
model: ES.Result,
url: '/search/query'
});
There are a few issues here:
A fetch should be a GET, not a POST, because a fetch should not save or modify anything
Maybe just a personal preference, but I'd url as a function, so as to avoid trying to modify the AJAX request options manually.
The fetch call will always be asynchronous, so you need to either add a success callback in the options hash, or add a listener to the collection's reset event
I'd write the collection like this:
ES.Results = Backbone.Collection.extend({
initialize: function() {
this.query = "test";
},
model: ES.Result,
url: function() {
return '/search/query?query=' + this.query;
}
});
Then set the search when you create the collection:
var resultsData = new ES.Results();
resultsData.query = "soccer";
And use success and/or the on("reset") event to handle the result:
resultsData.on("reset", function(collection) {
console.log(collection);
});
console.log("Fetching....");
resultsData.fetch({
success: function(collection, response) {
console.log("Got data!" + collection.length);
},
error: function(collection, response) {
console.log("Error: " + response.responseText);
}
});