11
votes

With backbone.js I'm saving a model. A PUT is send to the server and the response is returned. The first time I do it, it returns success, the following times an error is return, because after the first time the response is added to the model.

Save function in Backbone.js:

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

    return false;
},

PHP returns a JSON-string:

{"response": "Model saved!"}

Following PUT's get an error as response, because 'response' is added to the model:

Unknown column 'response' in 'field list'

Why is the response added to the model and how do I prevent it?

2
Couldn't you just do a conditional and skip the 'response' in your php script? - swatkins
I could, but I thought it would be cleaner to let the server side decide the response. - GijsjanB
Nope, I thought it would be cleaner if the response came from PHP (server side), but know, as dira suggests, I'm doing it client side. - GijsjanB

2 Answers

7
votes

From Backbone's documentation on model save:

Set a hash of model attributes, and sync the model to the server. If the server returns an attributes hash that differs, the model's state will be set again. http://documentcloud.github.com/backbone/docs/backbone.html#section-41

What to do to make it work: don't return {"response": "Model saved!"} from the server. Just return a success (status 200) with no content.

If the save did not work, return a JSON with the errors, and Backbone will trigger an error event on your model, with the JSON you provided (see http://documentcloud.github.com/backbone/docs/backbone.html#section-41 and http://documentcloud.github.com/backbone/docs/backbone.html#section-145).

7
votes

Just to resurrect an ancient thread...

It isn't always possible/desirable to change the response you get back from the server.

Another solution is to override parse in the model to take care of this. For your situation, where the response is inappropriate for ALL of your models, you could do it in a superclass.

MyModel = Backbone.Model.extend({
    parse: function(data) {
        delete data["success"];
        return data;
    }
});

Address = MyModel.extend({
    saveCountry: function() {
        this.model.save({},{
            success: function(model, response) {
                console.log('success! ' + response);
            },
            error: function(model, response) {
                console.log('error! ' + response);
            }
        });
        this.render();

        return false;
    },

    ...

});