{hero}

xhr

Since: DataTables 1.10

Ajax event - fired when an Ajax request is completed.

Description

When working with Ajax data, it is often useful to know when DataTables has completed the loading of data, so you can either manipulate that data into the format DataTables expects based upon its configuration (columns.data) or so you can use the data contained in the JSON response from the server for other parts of the page.

This event can be seen as the event complement to the ajax.dataSrc option (which can also be used to manipulate and intercept the data from the Ajax request). Generally you would want to do data manipulation in the dataSrc callback and use events for intercepting the data.

Note that this event is called before DataTables has processed the new data from the server, so the returned data will not have been drawn on page when this event fires.

Additionally, as of DataTables 1.10.7 this event is triggered by both success and error conditions when the Ajax request completed (i.e. it is always triggered regardless of the outcome of the Ajax request). Prior to 1.10.7 it was only triggered by a successful request. The json parameter (3rd passed in) for the event handler will be null if an error has occurred and the xhr parameter (4th) can be used to determine the error details if required.

Please note that, as with all DataTables emitted events, the event object has a DataTables API instance available on it (the first parameter). Additionally, the events are triggered with the dt namespace. As such, to listen for this event, you must also use the dt namespace by simply appending .dt to your event name, as shown in the example below.

Type

function function( e, settings, json, xhr )

Parameters:
Returns:

Since 1.10.7 you can return true to indicate to DataTables that it should not trigger its dt-error event if you have handled an error condition yourself.

Examples

Pre-process the data returned from the server:

$('#example')
	.on('xhr.dt', function (e, settings, json, xhr) {
		for (var i = 0, ien = json.aaData.length; i < ien; i++) {
			json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
		}
		// Note no return - manipulate the data directly in the JSON object.
	})
	.DataTable({
		ajax: 'data.json'
	});

Use a custom property returned from the server in another DOM element:

$('#example')
	.on('xhr.dt', function (e, settings, json, xhr) {
		$('#status').html(json.status);
	})
	.DataTable({
		ajax: 'data.json'
	});

Related

The following options are directly related and may also be useful in your application development.