1 /* global _wpUtilSettings */
2 window.wp = window.wp || {};
5 // Check for the utility settings.
6 var settings = typeof _wpUtilSettings === 'undefined' ? {} : _wpUtilSettings;
11 * Fetch a JavaScript template for an id, and return a templating function for it.
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 * Underscore's default ERB-style templates are incompatible with PHP
21 * when asp_tags is enabled, so WordPress uses Mustache-inspired templating syntax.
23 * @see trac ticket #22344.
26 evaluate: /<#([\s\S]+?)#>/g,
27 interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
28 escape: /\{\{([^\}]+?)\}\}(?!\})/g,
32 return function ( data ) {
33 compiled = compiled || _.template( $( '#tmpl-' + id ).html(), null, options );
34 return compiled( data );
41 // Tools for sending ajax requests with JSON responses and built in error handling.
42 // Mirrors and wraps jQuery's ajax APIs.
44 settings: settings.ajax || {},
47 * wp.ajax.post( [action], [data] )
49 * Sends a POST request to WordPress.
51 * @param {string} action The slug of the action to fire in WordPress.
52 * @param {object} data The data to populate $_POST with.
53 * @return {$.promise} A jQuery promise that represents the request.
55 post: function( action, data ) {
57 data: _.isObject( action ) ? action : _.extend( data || {}, { action: action })
62 * wp.ajax.send( [action], [options] )
64 * Sends a POST request to WordPress.
66 * @param {string} action The slug of the action to fire in WordPress.
67 * @param {object} options The options passed to jQuery.ajax.
68 * @return {$.promise} A jQuery promise that represents the request.
70 send: function( action, options ) {
71 if ( _.isObject( action ) ) {
74 options = options || {};
75 options.data = _.extend( options.data || {}, { action: action });
78 options = _.defaults( options || {}, {
80 url: wp.ajax.settings.url,
84 return $.Deferred( function( deferred ) {
85 // Transfer success/error callbacks.
86 if ( options.success )
87 deferred.done( options.success );
89 deferred.fail( options.error );
91 delete options.success;
94 // Use with PHP's wp_send_json_success() and wp_send_json_error()
95 $.ajax( options ).done( function( response ) {
96 // Treat a response of `1` as successful for backwards
97 // compatibility with existing handlers.
98 if ( response === '1' || response === 1 )
99 response = { success: true };
101 if ( _.isObject( response ) && ! _.isUndefined( response.success ) )
102 deferred[ response.success ? 'resolveWith' : 'rejectWith' ]( this, [response.data] );
104 deferred.rejectWith( this, [response] );
105 }).fail( function() {
106 deferred.rejectWith( this, arguments );