jQuery ajaxError() Method (original) (raw)

Last Updated : 12 Jul, 2023

The **ajaxError() method in jQuery is used to specify a function to be run when an AJAX request fails.

**Syntax:

$(document).ajaxError( function(event, xhr, options, exc) )

**Parameters: This method accepts single parameter function which is mandatory. This function accepts four parameters which are listed below:

The demo.txt file is stored on the server and it will load after clicking the **change content button.

**demo.txt

This is GFG.

**Example 1: This example changes the content of

element, by taking the data from server. When the AJAX request fails due to an error, the page says

**AJAX request fails.

html `

<!-- Script to use ajaxError() method -->
<script>
    $(document).ready(function () {
        $(document).ajaxError(function () {
            alert("AJAX request fails.");
        });

        $("button").click(function () {
            $("#paragraph").load("demo.txt");
        });
    });
</script>
<div id="div_content">

    <h1 style="color: green;">
        GeeksforGeeks
    </h1>

    <p id="paragraph" style="font-size: 20px;">
        A computer science portal for geeks
    </p>
</div>

<button>
    Change Content
</button>

`

**Output:

jquery-74

**Example 2: This example changes the content of

element, by taking the data from the server. When the AJAX request fails due to an error, the page says **AJAX request fails.

**demo.txt

This is GFG.

html `

<!-- Script to use ajaxError() method -->
<script>
    $(document).ready(function () {
        $(document).ajaxError(function () {
            alert("AJAX request fails.");
        });

        $("button").click(function () {
            $("#heading").load("demo.txt");
        });
    });
</script>
<div id="div_content">

    <h1 id="heading" style="color: green;">
        GeeksforGeeks
    </h1>

    <p style="font-size: 20px;">
        A computer science portal for geeks
    </p>
</div>

<button>
    Change Content
</button>

`

**Output:

jquery-75