JQuery. $.post request .done() .fail() avoid code duplication

14,221

Solution 1

You can use always callback method, and the request will always go in that block. As you know when data contains error and not, this method will work for server-side errors. And you can catch client-side errors by defining the final else block.

$.post("test", {
    ajax: "true",
    action: ""
}).always(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        //handle server-side errors
    } else {
        //handle client-side errors like 404 errors
    }
});

Solution 2

The most obvious and simple solution would be to simply have a failure callback like so:

function ajaxFailed() {
    // yyy
}

$.post("test", {
    ajax: "true",
    action: ""
}).done(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        ajaxFailed();
    }
}).fail(ajaxFailed);

Solution 3

Have them call the same function, e.g.

function onErr() { 
    //yyy
}
$.post("test", {
    ajax: "true",
    action: ""
}).done(function(data){
    if (data == "ok"){
        //xxx
    } else if (data == "err"){
        onErr();
    }
}).fail(onErr);
Share:
14,221

Related videos on Youtube

Igor Slipko
Author by

Igor Slipko

Updated on July 07, 2022

Comments

  • Igor Slipko
    Igor Slipko almost 2 years

    I have a post request like

      $.post("test", {
        ajax: "true",
        action: ""
      }).done(function(data){
        if (data == "ok"){
            //xxx
        } else if (data == "err"){
            //yyy
        }
      }).fail(function(){
        //yyy
      });
    

    How to avoid code duplication in the post request if code in .done() method (comment 'yyy') the same in fail method (comment 'yyy') ??

  • John Dvorak
    John Dvorak over 11 years
    I don't think you'll get data=="err" when the request fails.
  • Rudi Visser
    Rudi Visser over 11 years
    I'm pretty sure the data=="err" is for when the request fails at the server side, not client. Exactly like @JanDvorak said.
  • halilb
    halilb over 11 years
    you're right. data == 'err' will work for server side errors. I added the last else block to catch client-side errors.