How to handle server responses in dojo/store/JsonRest? - javascript

When using 'add' or 'put' on a dojo/store/JsonRest store, I would like to have an event handler for the server response, either on error or success.
I have tried adding an option like error: function() {} to the 'add' call, but this does not get triggered. Is there a special event or option that deals with the server response?

OK, so the answer is to use then, as it seems the add method returns a Deferred.
So you can do: store.add(...).then(function(value){ /* success */ }, function(error){ /* error */ })

Related

Cancel jQuery ajax error in .fail() function

I'm working on a site that has a global Ajax error handler in the main page template, like this:
$(document).ajaxError(function (event, request, settings, thrownError) {
postError(thrownError);
})
This updates the page with information about an error from an Ajax request. I am working on a specific Ajax call where I need errors to be handled differently, it will just silently select a value without doing anything about the error. The function is in a handler for a DevExtreme SelectBox that must return a Promise:
return $.ajax({
// stuff
}).fail(function (request, status, error) {
// set value
});
This does what its supposed to in regards to setting the value, but the Ajax error handler still fires. I've tried setting the error to null in the .fail() function but it still gets posted. Is there a way to disable the ajaxError handler for just this one call?
Seems like you want to prevent bubbling the error up for a particular case. See the following post and I believe this is what you are looking for:
Javascript: How to stop multiple jQuery ajax error handlers?
Hope this helps!

Invoke jQuery ajaxSuccess (or any global AJAX event) even if the local success (or any local AJAX event) throws an error

It is not mentioned in the docs, but apparently if the local AJAX success handler throws an error, even the global ajaxSuccess handler is not invoked. Is there a way around this mechanism cause if you want to distribute a JS library or util function that does something on ajaxSuccess, you can't necessarily have control over the success handler and make sure it does not raise an exception.
$(document).ajaxSuccess(function(ev, jqXHR, settings) {
console.log('ajaxSuccess called!'); // does not get called
});
$.ajax({
'url': '/',
'type': 'GET',
'success': function (response) {
console.log('success called!');
throw new Error();
}
});
CodePen: http://codepen.io/anon/pen/Ldybr
Here is the documentation that partially explains the issue you're facing:
Events
...
success (Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
ajaxSuccess (Global Event)
This event is also only called if the request was successful.
error (Local Event)
This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
ajaxError (Global Event)
This global event behaves the same as the local error event.
This is the normal flow of events, i.e. any global event is called after local. But in case any callback throws exception, no other callback is called, because jQuery internally doesn't wrap the callback in try-catch (you may do this locally in your callback though).
Another solution, as I've mentioned in comments, is dataFilter property of ajax options, which allows you to perform needed actions before any local callback (success or error) is called. Here is demo from my comments to the question, just in case:
$.ajaxSetup({
dataFilter: function(data, type) {
console.log('dataFilter called!');
return data;
}
});

Backbone.js 'error' event: how do I know which method (fetch, save, delete) triggered it?

Backbone sync triggers an error event on the model/collection whenever the response is not a 200 status code. In order to implement a default error handling mechanism, I am listening for the error event in my views. This works, but I want to be able to distinguish between errors saving (save), deleting (delete), and retrieving (fetch).
So, in a nutshell, this is sort of what I want:
var MyView = Backbone.View.extend({
initialize: function(options){
this.listenTo(this.model, 'error', this.errorHandler);
},
errorHandler: function(model, xhr, options){
// logic would depend on whether the event was triggered by fetch,
// save, or delete
// How can I tell how the event was triggered?
}
});
Does Backbone provide me a way to do that? Does the jqXHR object? Looking for options here.
I know that I could (and some would say, should) use the error callback in options to fetch, etc. but I don't want to have to modify a lot of existing code to create the default behavior.
Do I need to override fetch, save, and delete in a base model to namespace the event or is there something already built in?
Thanks
The callback for Backbones error-event has 3 parameters: model, xhr and options (in that order).
The options object refers to the options that were used to triggered the (failed request. So with in it, you should be able to see what HTTP method was used (I think ti's called "type"?), the statusCode and even the URL it was trying to send the request to.

backbone.js model.save doesn't set the id

I've inherited a backbone js based app. I really like backbone and i'm just starting to get my head around it. From my understanding when model.save is called on a new entity it should post that to the server, the server should return the same json but with an id alloted and backbone should persist that id to the model so that further saves result in a PUT with the ID for update.
However, when I call model.save() and then try to get the model.id property, it's null.
Is this because I'm not doing it with a call back? So the property hasn't been set yet?
How would I set the success callback? calling model.save({success: function(){...}})doesn't work?
here is the actual call:
model.save(null, {
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
Something feels odd about this. Setting silent: true only makes it so none of the events get fired. Everything else should happen normally. In other words, don't assume that setting slient: true is the right answer here...
I suspect you are actually throwing an exception some place (probably with validation or something like that) and somehow, setting silent: true is causing everything to flow through.
I would strongly suggest that you remove this option and check your console or run with the debugger... I suspect you have a bug lurking around there some place.
Some suggestions: Take a look at the annotated source for the model.set function. It gets called before your success callback will get called. Inside of that function, there are several things that will happen if silent is false. These include validation, individual property change triggers, and a global change trigger. I would bet money that either the validation is failing or something that is listening to the changes is throwing an exception.
i needed to set the silent: true on the save:
model.save(null, {
silent: true,
success: function () {
alert('success');
},
error: function () {
alert('error');
}
});
I had the same issue, turned out to be because my custom parse was failing

JQuery error property for error handler

I'm just playing around for the first time with jQuery's ajax functionality. I wanted to add a function that could handle any errors. So, in one of my client javascript blocks, I added the following line:
<script type="text/javascript">
....
$.ajax({ error: function () { alert('boo'); } })
....
</script>
I expected that this would bind the error handler, so that when an error occurs, it would fire the anonymous function included.
What happens instead though, is that it immediately fires the function on page load, as soon as it parses this line of code.
What am I doing wrong? What is the proper way to bind the ajax error handler?
I'm not sure if I understood your question correctly, let me know if I've misunderstood.
I assume that you are trying to create a generic ajax call error handler? If that's the case, you have got the wrong idea.
Are you are just trying to bind the event handler? In this case, you are executing it.
I would recommend you read and check out the examples on these jQuery API reference docs:
API/1.3/Events
Ajax/jQuery.ajax
Also check out the post link provided by F.Aquino and this SO post: JavaScript Exception Handling.
This is could be helpful too: Handling AJAX Errors With jQuery.
You want to change the global settings. Check jQuery documentation.
$.ajaxSetup({
error: function () { alert('boo'); }
});

Categories