Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to override the Jquery.ajax function?

Tags:

jquery

I want to override the $.ajax function in Jquery

I want to use the existing functionality and need to add some other functionality

Example:

get the original ajax function in to OriginalAjax variable

 var OriginalAjax = $.ajax 

  $.ajax = function(xhr){

      if(xhr.status ==401)
       {
          // Diplay Error in dialog box;
       }
      return(OriginalAjax(xhr));
  });

is it possible to override the $.ajax function? if 'Yes' Please let know how to implement it?

like image 957
Srikanth Chilukuri Avatar asked Sep 26 '12 05:09

Srikanth Chilukuri


People also ask

What is jqXHR in AJAX?

The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.

Which jQuery function is used to send AJAX request using get method?

jQuery - AJAX get() and post() Methods. The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.

What is dataType in AJAX call?

dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. "text": A plain text string. So you want contentType to be application/json and dataType to be text : $.


1 Answers

Yes, you can do that...

var oldAjax = $.ajax;

$.ajax = function() {
     // Do your magic.
     return oldAjax.apply($, arguments);
};

...or...

const oldAjax = $.ajax;

$.ajax = (...args) => {
     // Do your magic.
     return oldAjax(...args);
};

However, judging by your example, you should just use a global event handler such as ajaxComplete(), where you can check the response status.

like image 184
alex Avatar answered Nov 15 '22 07:11

alex