Search code examples
jqueryajaxjeditable

Jeditable - detect ajax error


Is there some code I can add to Jeditable to raise an error if the XHR request I'm using returns something other than HTTP 200 (e.g. if there's an internal server error or the server times out completely)?

I tried adding the callback parameter (below), but it only seems to fire when the AJAX request is successful...

   $('.foo').editable('/user/ajax_edit_full_name', 
       {
        indicator: 'Saving...',
        cancel : 'Cancel',
        submit : 'Save',
        cssclass : 'editable',
        callback : function(value, settings) {
             console.log(this);
             console.log(value);
             console.log(settings);
         }
       }
   ); 

Update: Further to Bruno's answer, besides the 'status' property, xhr has, amongst other things, xhr.statusText. So in my case, if they specify an empty name (which is invalid) I've set the server to send an error 400 plus a custom message, and the latter is displayed.


Solution

  • Accordingly to the Jeditable source code there's a parameter called onerror

    @param Function options[onerror]  function(settings, original, xhr) { ... } called on error
    

    Thus, it's possible to achieve what you are trying to do by adding the parameter onerror on your editable function. The onerror parameter expects as argument a function in the following format:

    function(settings, original, xhr) { ... }
    

    Where the xhr parameter is your XHR Object. So, instead of trying to catch the error on your on, you can simply treat then inside your onerror function. Like the following:

    $('.foo').editable('/user/ajax_edit_full_name', 
    {
        indicator: 'Saving...',
        cancel : 'Cancel',
        submit : 'Save',
        cssclass : 'editable',
        onerror : function(settings,original,xhr){
            alert("It wasn't possible to edit. Try again");
            console.log("XHR Status: " + xhr.status);
        },
        callback : function(value, settings) {
             console.log(this);
             console.log(value);
             console.log(settings);
         }
    }); 
    

    I hope it helped.