1
/* global _wpUtilSettings */
2
window.wp = window.wp || {};
5
// Check for the utility settings.
6
var settings = typeof _wpUtilSettings === 'undefined' ? {} : _wpUtilSettings;
11
* Fetches a template by id.
13
* @param {string} id A string that corresponds to a DOM element with an id prefixed with "tmpl-".
14
* For example, "attachment" maps to "tmpl-attachment".
15
* @return {function} A function that lazily-compiles the template requested.
17
wp.template = _.memoize(function ( id ) {
20
evaluate: /<#([\s\S]+?)#>/g,
21
interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
22
escape: /\{\{([^\}]+?)\}\}(?!\})/g,
26
return function ( data ) {
27
compiled = compiled || _.template( $( '#tmpl-' + id ).html(), null, options );
28
return compiled( data );
35
// Tools for sending ajax requests with JSON responses and built in error handling.
36
// Mirrors and wraps jQuery's ajax APIs.
38
settings: settings.ajax || {},
41
* wp.ajax.post( [action], [data] )
43
* Sends a POST request to WordPress.
45
* @param {string} action The slug of the action to fire in WordPress.
46
* @param {object} data The data to populate $_POST with.
47
* @return {$.promise} A jQuery promise that represents the request.
49
post: function( action, data ) {
51
data: _.isObject( action ) ? action : _.extend( data || {}, { action: action })
56
* wp.ajax.send( [action], [options] )
58
* Sends a POST request to WordPress.
60
* @param {string} action The slug of the action to fire in WordPress.
61
* @param {object} options The options passed to jQuery.ajax.
62
* @return {$.promise} A jQuery promise that represents the request.
64
send: function( action, options ) {
65
if ( _.isObject( action ) ) {
68
options = options || {};
69
options.data = _.extend( options.data || {}, { action: action });
72
options = _.defaults( options || {}, {
74
url: wp.ajax.settings.url,
78
return $.Deferred( function( deferred ) {
79
// Transfer success/error callbacks.
80
if ( options.success )
81
deferred.done( options.success );
83
deferred.fail( options.error );
85
delete options.success;
88
// Use with PHP's wp_send_json_success() and wp_send_json_error()
89
$.ajax( options ).done( function( response ) {
90
// Treat a response of `1` as successful for backwards
91
// compatibility with existing handlers.
92
if ( response === '1' || response === 1 )
93
response = { success: true };
95
if ( _.isObject( response ) && ! _.isUndefined( response.success ) )
96
deferred[ response.success ? 'resolveWith' : 'rejectWith' ]( this, [response.data] );
98
deferred.rejectWith( this, [response] );
100
deferred.rejectWith( this, arguments );