diff --git a/src/js/_enqueues/wp/util.js b/src/js/_enqueues/wp/util.js
index e29fd3be462e8..86faea6909495 100644
--- a/src/js/_enqueues/wp/util.js
+++ b/src/js/_enqueues/wp/util.js
@@ -112,7 +112,7 @@ window.wp = window.wp || {};
delete options.error;
// Use with PHP's wp_send_json_success() and wp_send_json_error().
- deferred.jqXHR = $.ajax( options ).done( function( response ) {
+ deferred.jqXHR = $.ajax( options ).done( function( response, textStatus, jqXHR ) {
// Treat a response of 1 as successful for backward compatibility with existing handlers.
if ( response === '1' || response === 1 ) {
response = { success: true };
@@ -127,10 +127,10 @@ window.wp = window.wp || {};
action &&
action.data &&
'query-attachments' === action.data.action &&
- deferred.jqXHR.hasOwnProperty( 'getResponseHeader' ) &&
- deferred.jqXHR.getResponseHeader( 'X-WP-Total' )
+ jqXHR &&
+ jqXHR.getResponseHeader( 'X-WP-Total' )
) {
- context.totalAttachments = parseInt( deferred.jqXHR.getResponseHeader( 'X-WP-Total' ), 10 );
+ context.totalAttachments = parseInt( jqXHR.getResponseHeader( 'X-WP-Total' ), 10 );
} else {
context.totalAttachments = 0;
}
diff --git a/tests/qunit/index.html b/tests/qunit/index.html
index 5054ff954518d..73b96b11f43aa 100644
--- a/tests/qunit/index.html
+++ b/tests/qunit/index.html
@@ -189,6 +189,7 @@
+
diff --git a/tests/qunit/wp-includes/js/wp-util.js b/tests/qunit/wp-includes/js/wp-util.js
new file mode 100644
index 0000000000000..e6ab1945f8f16
--- /dev/null
+++ b/tests/qunit/wp-includes/js/wp-util.js
@@ -0,0 +1,26 @@
+/* global wp, jQuery */
+
+QUnit.module( 'wp.ajax.send', {
+ beforeEach: function() {
+ this.originalAjax = jQuery.ajax;
+ },
+ afterEach: function() {
+ jQuery.ajax = this.originalAjax;
+ }
+} );
+
+QUnit.test( 'query-attachments request that completes synchronously should set totalAttachments', function( assert ) {
+ const jqXHR = { getResponseHeader: () => '42' };
+ const context = {};
+
+ jQuery.ajax = function( options ) {
+ const deferred = jQuery.Deferred();
+ deferred.done( options.success );
+ deferred.resolveWith( options.context, [ { success: true, data: [] }, 'success', jqXHR ] );
+ return deferred.promise();
+ };
+
+ wp.ajax.send( { data: { action: 'query-attachments' }, context: context } );
+
+ assert.strictEqual( context.totalAttachments, 42, 'totalAttachments is read from the X-WP-Total header' );
+} );