Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exec function before every ajax success callback

I have a website where I rely on a lot of custom API call. My API return always an XML.

Currently, at the start of each and every $.get or $.post I call, I have this snippet :

var root = $($.parseXML(data)).find("Response");

if (root.children("Type").text() == "Error") {
  toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
  return;
}

However, I feel this code to be much redundant on one of my page, it's used 15 times.

I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here

Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?

like image 816
Remy Grandin Avatar asked Jun 09 '26 08:06

Remy Grandin


1 Answers

I assume that you have something like this in many places in your code

$.ajax({
    method: "GET",
    url: "someurl.html",
    dataType: "xml",
    success : function() {
        var root = $($.parseXML(data)).find("Response");
        if (root.children("Type").text() == "Error") {
          toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
          return;
        }
        // ...
    },
    error : function(qXHR, textStatus, errorThrown){
        toastr.error(errorThrown, "Error " + qXHR.status);
    }
});

you could create a generic custom ajax function tha you can re-use

function baseAjaxCall(option, sCb) {    
    var ajaxOptions = {
        method: option.method || "GET",
        url: option.url,
        dataType: option.dataType || "xml",
        success : function(data) {
            var root = $($.parseXML(data)).find("Response");
            if (root.children("Type").text() == "Error") {
              toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
              return;
            }
            else {
                sCb(root);
            }
        },
        error : function(qXHR, textStatus, errorThrown){
            toastr.error(errorThrown, "Error " + qXHR.status);
        }
    };
    //you can check for optional settings
    if(option.contentType  !== undefined){
        ajaxOptions.contentType = option.contentType;
    }

    $.ajax(ajaxOptions);
}

everywhere in your code you can re-use the baseAjaxCall function

baseAjaxCall({ url: "someurl.html" }, function(root){
 // no need to chek for errors here!
});

Hope it's helps!

like image 55
gon250 Avatar answered Jun 11 '26 22:06

gon250



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!