I'm overriding the fetch method of a Backbone Collection to send a request to a different url in certain circumstances, and I have to send some data with it. The new fetch method (copied from another SO answer) looks like this
fetch(options){
if(options && options.data){
options = _.extend({url : '/someendpoint/'}, options || {});
}
return Backbone.Collection.prototype.fetch.call(this, options);
}
When I call the fetch method in a view, I pass it some data (that comes in with the options parameter in fetch)
callFetchMethod(){
var min = $("#min").val();
var max = $("#max").val();
var range = {};
range['min'] = min;
range['max'] = max;
mycollection.fetch({'data': range}); //send the object with min and max to collection
}
The problem is that the data object is not being recognized on the server. I've tried calling JSON.stringify(range)
before sending it to the Collection and also JSON.stringify(options.data)
inside the collection, but all to no avail.
I need to use a new url and I need to send data to the server. How can I do it in the fetch method above?
Update: this is what happens in various attempts to stringify the whole options object or just options.data
If I stringify the whole options object like this
if (options && options.data){ options = _.extend({url: '/someendpoint'}, options || {}); options.data = JSON.stringify(options); console.log(options, "options in collection"); }
no data gets sent to the server (and the right url isn’t called)
{"url":"/someendpoint","data":"{\"min\":\"1429740602093\",\"max\":\"1429740602093\"}"}
if I stringify options.data like this
if (options && options.data){
options = _.extend({url: '/someendpoint'}, options || {});
options.data = JSON.stringify(options.data);
console.log(options, "options in collection");
}
this is out output in the console
Object {url: "/someendpoint", data: "{"min":"1429740602093","max":"1429740602093"}"} "options in collection"
and I get an error on the server that says
the server throws an unexpected end of JSON input error