How to clear defaults from $.ajaxSetup()?

Viewed 220

I am using $.ajaxSetup() to set some default ajax parameters. But I want to clear those defaults from after it is used. How can I do that? I searched in Google but I found only workarounds.

PS: I know $.ajaxSetup() is strongly recommended to not use but let's take this as an exception.

1 Answers

Only way how I managed to remove the set values, was to replace them with different values. Undefined did not help nor empty array. It seems you have to directly remove the parameter that you set before. Note that this does not actually reset the values but overwrites them with null (or whatever value you use) and may result in other errors or you will have to write all options with original defaults to be set.

As per documentation:

This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

Example:

function set() {
  // Set ajax defaults
  $.ajaxSetup({
    url: "https://www.google.com",
    cache: false,
    type: "POST"
  });
}

function remove() {
  // Remove ajax default
  $.ajaxSetup({
    url: null,
    cache: true
  });
}

function call() {
  // Call ajax with defaults
  $.ajax({
    complete: function(data, status) {
      // We are done show what we called
      $("#result").html("URL: " + this.url + "<br>cache: " + this.cache + "<br>type: " + this.type);
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="set();">Set defaults</button>
<button onclick="remove();">Remove defaults</button>
<button onclick="call();">Perform AJAX call</button>
<div id="result">No value.</div>

Related