I have customized the fetch method of a Backbone Collection to make a request to a different URL under certain conditions, and I need to include some data with it. The modified fetch method (which I obtained from another solution on Stack Overflow) is as follows:
fetch(options){
if(options && options.data){
options = _.extend({url : '/someendpoint/'}, options || {});
}
return Backbone.Collection.prototype.fetch.call(this, options);
}
When I invoke the fetch method in a view, I supply it with some data within the options parameter of the fetch call.
callFetchMethod(){
var min = $("#min").val();
var max = $("#max").val();
var range = {};
range['min'] = min;
range['max'] = max;
mycollection.fetch({'data': range}); //sending the object with min and max values to the collection
}
The issue I am facing is that the server does not recognize the data object. I have attempted to use JSON.stringify(range)
before sending it to the collection and also JSON.stringify(options.data)
inside the collection, but so far, none of these attempts have been successful.
I must utilize a new URL and send data to the server. How can I achieve this using the fetch method provided above?
Update: This is a summary of the outcomes when trying to stringify either the entire 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 is sent to the server (and the correct URL is not accessed)
{"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 the output in the console
Object {url: "/someendpoint", data: "{"min":"1429740602093","max":"1429740602093"}"} "options in collection"
And the server throws an error stating
The server encounters an unexpected end of JSON input error