Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger the success callback on a model.save()?

Tags:

backbone.js

this.model.save({
  success: function(model, response){
    console.log('success');
  },
  error: function(){
    console.log('error');
  }
})

The model is correctly posted to the server which handles the save, but the success callback is not fired. Do I need to send something back from the server ?

like image 822
Running Turtle Avatar asked Apr 22 '11 16:04

Running Turtle


4 Answers

The first argument of save is the attributes to save on the model:

this.model.save( {att1 : "value"}, {success :handler1, error: handler2});
like image 55
Julien Avatar answered Oct 23 '22 17:10

Julien


For some unknown reason, none of the above method worked for me. The api only was not hit in my case.

But later while searching on this, I bumped into this link, where some one had tried null instead of {} as the first parameter.

this.model.save(null, {
    success: function (model, response) {
        console.log("success");
    },
    error: function (model, response) {
        console.log("error");
    }
});

so, this worked for me. Hope this helps you too.

like image 25
Yasser Shaikh Avatar answered Oct 23 '22 18:10

Yasser Shaikh


Your server must return a JSON object. If the response is not a JSON object, the callbacks will not fire.

If for success your server doesn't return a JSON object, perform a save with dataType:"text" option, like this:

this.model.save([],{
 dataType:"text",
 success:function() {},
 error:function() {}
});

With this option it will not be waiting for a JSON in response, but a text, and thus the callback will be launched.

like image 38
Igor G. Avatar answered Oct 23 '22 18:10

Igor G.


You may use underscore lib as follows as backbone already depends upon this. Remember first argument of save must either have attributes or you may just pass {} in case you want to save model itself.

this.model.save({}, _.bind(function(model, response){
  //Do whatever you want e.g.
  this.collection.add(model)
}, this))
like image 11
Pradeep Kumar Mishra Avatar answered Oct 23 '22 18:10

Pradeep Kumar Mishra