I have an ajax request in my javascript that is sending data to a Rails controller. If the controller finds that the data is duplicate of information already in the database, it returns an ‘Unprocessable Entity’ error.
I would like to have a dialog open and ask a user if he is sure he wants to insert the duplicate information. If the user says yes, I’d like to add another key to the data object and retry the request. The key added would be a flag that ignores the duplicate check and inserts the data anyway.
$.ajax({
url: '/url',
type: 'post',
data: this.buildData(),
success: function() {
bootbox.alert('Information added', function() {
Backbone.history.loadUrl();
}.bind(this)
);
}.bind(this),
error: function(jqXHR, textStatus, errorThrown) {
if(errorThrown === 'Unprocessable Entity') {
bootbox.confirm('Do it anyway?', function(confirm) {
if(confirm) {
/*Here I want to add another key to the data object and resend the request*/
}
}.bind(this)
);
}
}.bind(this)
});
How would I go about doing this, or better yet, is there a better way of doing what I am trying to accomplish?
First of all I am sure there is some plugin for that.
But if no plugin is suitable you can always do something like this
give me some time to make sure this runs properly and give full code
Another way you might be interested is using synchronous call.
{"async":false}in JQuery’s ajax request.I know this might seem to defeat the purpose, however I found it quite useful for server side validation – so it might suite your needs and you won’t have to deal with complicated handlers as I show above, it would simply be something like this :