Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a good response from saving a model

Tags:

backbone.js

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?

like image 368
GijsjanB Avatar asked Oct 20 '11 13:10

GijsjanB


1 Answers

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).

like image 134
dira Avatar answered Jan 03 '23 18:01

dira