I have the following code to create a new model to a collection. The underlying datastore is a remote API:
var postCreationStatus = this.model.create(newPostModel, {
wait : true // waits for server to respond with 200 before adding newly created model to collection
}, {
success : function(resp){
console.log('success callback');
console.log(resp);
},
error : function(err) {
console.log('error callback');
console.log(err);
}
});
The new model gets created, and I can confirm this from the database, but neither the success nor the error callbacks get called.
After the creation has been pleted, I want to redirect the user. Redirecting prematurely kills the AJAX request, which is why it is important I use the success callback.
The server responds with a JSON response { id : 11 }
and an HTTP status of 200 OK
.
I have the following code to create a new model to a collection. The underlying datastore is a remote API:
var postCreationStatus = this.model.create(newPostModel, {
wait : true // waits for server to respond with 200 before adding newly created model to collection
}, {
success : function(resp){
console.log('success callback');
console.log(resp);
},
error : function(err) {
console.log('error callback');
console.log(err);
}
});
The new model gets created, and I can confirm this from the database, but neither the success nor the error callbacks get called.
After the creation has been pleted, I want to redirect the user. Redirecting prematurely kills the AJAX request, which is why it is important I use the success callback.
The server responds with a JSON response { id : 11 }
and an HTTP status of 200 OK
.
- 1 this title is incorrect, this question is not about collection.create – Alexander Mills Commented Mar 14, 2015 at 4:30
1 Answer
Reset to default 6Looking into the backbone code, I realized my call to the create()
function was incorrect. The success and error callbacks needed to be within the object being passed in as the second argument, and not as a third argument. The changed, and working snippet is this:
var postCreationStatus = this.model.create(newPostModel, {
wait : true, // waits for server to respond with 200 before adding newly created model to collection
success : function(resp){
console.log('success callback');
console.log(resp);
that.redirectHomePage();
},
error : function(err) {
console.log('error callback');
// this error message for dev only
alert('There was an error. See console for details');
console.log(err);
}
});