Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.ajaxPrefilter() Vs $.ajaxSetup() - jQuery Ajax

While learning through ajax in jQuery, I came across 2 terms, viz., $.ajaxPrefilter() and $.ajaxSetup(). All I can find out is that these make some changes in AJAX before loading or making call to $.ajax().

Can someone simplify and explain these terms in easiest form along with a slight comparison of the two?

like image 700
Deadpool Avatar asked Apr 24 '15 09:04

Deadpool


People also ask

What is jQuery ajaxPrefilter?

ajaxPrefilter( [dataTypes ], handler )Returns: undefined. Description: Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $. ajax() .

What is ajaxSetup?

The ajaxSetup() method in jQuery is used to set the default values for future AJAX requests. Syntax: $.ajaxSetup( {name:value, name:value, ... } )

Which of the following is the lowest level jQuery ajax function?

ajax(): It is considered to be the lowest level and basic functions. It is used to send requests. This function can be performed without a selector. 2.


2 Answers

$.ajaxSetup() - Set default values for future Ajax requests. You could, for example, set the ajax URL that you always want to use for every request here.

Example:

$.ajaxSetup({
  // Always use this URL for every request
  url: "http://example.com/ajax.php"
});

$.ajaxPrefilter() - Modify existing options before each request is sent. You could, for example, append a query string component to every ajax request that is sent out.

Example:

$.ajaxPrefilter( function(options) {
    // Always add "?debug=1" to every URL
    options.url += (options.url.indexOf("?") < 0 ? : "?" : "&") + "debug=1";
});
like image 59
Drakes Avatar answered Oct 15 '22 06:10

Drakes


$.ajaxSetup simply takes an options object, and uses it as the defaults for future $.ajax() calls (and other calls that are shortcuts for this, like $.get). For instance,

$.ajaxSetup( { dataType: 'json' });

makes this the default dataType for future calls.

$.ajaxPrefilter lets you run a custom function before sending each AJAX request to the server. It can examine the options to that call, and then change them in any way that it wants. So it provides much more flexibility and control than $.ajaxSetup.

like image 45
Barmar Avatar answered Oct 15 '22 04:10

Barmar