Set default options for Ajax using jQuery ajaxSetup Method

jQuery $.ajaxSetup() method sets default option for all Ajax requests. This applies to all Ajax including $.get(), $.ajax() etc.

Syntax:

$.ajaxSetup(object);

object is json object of parameters with below name:value.

The following example shows the $.ajaxSetup() method setups default options:

<!DOCTYPE html>
<html>
<body>
    <p id="paragraph"></p>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $.ajaxSetup({
            url: 'https://api.agify.io/',
            type: 'post',
            data: 'name=jitesh',
            success: function(data) {
                $('#paragraph').text(data.name+' is '+data.age+' years old.');
            },
            error: function(error) {
                $('#paragraph').text('Something went wrong');
            }
        });
        $.ajax();
    </script>
</body>
</html>

If you want to change default option for any specific key, then you can define it into specific Ajax request. For example, if you want to change data, you can specify it in Ajax request.

<!DOCTYPE html>
<html>
<body>
    <p id="paragraph"></p>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script type="text/javascript">
        $.ajaxSetup({
            url: 'https://api.agify.io/',
            type: 'get',
            data: 'name=jitesh',
            success: function(data) {
                $('#paragraph').text(data.name+' is '+data.age+' years old.');
            },
            error: function(error) {
                $('#paragraph').text('Something went wrong');
            }
        });
        $.ajax({data: 'name=hardik'});
    </script>
</body>
</html>

You can also add or change options by adding new $.ajaxSetup() function. For example:

<p id="paragraph"></p>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
    $.ajaxSetup({
        url: 'https://api.agify.io/',
        type: 'post',
        data: 'name=jitesh',
        success: function(data) {
            $('#paragraph').text(data.name+' is '+data.age+' years old.');
        },
        error: function(error) {
            $('#paragraph').text('Something went wrong');
        }
    });
    $.ajaxSetup({type: 'get', data: 'name=hardik'});
    $.ajax();
</script>

I hope it will help you.

Tags: