Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Backbone fetch to always use POST

I have a Collection that needs to POST some data to its url to get the data it needs. The answer to these two questions, Fetch a collection using a POST request? and Overriding fetch() method in backbone model, make it seem like I should be able to get it to work like this:

fetch: function( options ) {
  this.constructor.__super__.fetch.apply(this, _.extend(options,{data: {whatever: 42}, type: 'POST'}));
}

, but Firebug still shows me a 404 error that is happening because a GET is being executed against the url in question (and the underlying Rails route only allows POST). Should this be working? If so, what else might I try? If not, what have I done wrong?

like image 984
cbmanica Avatar asked Mar 11 '13 22:03

cbmanica


1 Answers

After reading the question again, here's a way to force the fetch to use POST per fetch call. (Thanks for the comments)

yourCollection.fetch({
    data: $.param({id: 1234}), 
    type: 'POST', 
    success: function(d){
        console.log('success');
    }
});

Another approach is to override the AJAX implementation itself to use POST for all calls.

Backbone.ajax = function() {
    var args = Array.prototype.slice.call(arguments, 0);
    _.extend(args[0], { type: 'POST' });
    return Backbone.$.ajax.apply(Backbone.$, args);
};
like image 180
Dennis Rongo Avatar answered Nov 05 '22 19:11

Dennis Rongo