Reset cacheCode when flushing dynamic resources
[civicrm-core.git] / js / crm.ajax.js
CommitLineData
53f2643c
CW
1// https://civicrm.org/licensing
2/**
3 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface
4 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Ajax+Pages+and+Forms
5 */
1c1c1ae2 6(function($, CRM, undefined) {
53f2643c 7 /**
8d83b77c
CW
8 * @param string p - url
9 * @param string|object params
10 * @param string mode - optionally specify "front" or "back"
53f2643c 11 */
8d83b77c
CW
12 var tplURL;
13 CRM.url = function (p, params, mode) {
53f2643c 14 if (p == "init") {
8d83b77c 15 return tplURL = params;
53f2643c 16 }
8d83b77c 17 if (!tplURL) {
53f2643c
CW
18 console && console.log && console.log('Warning: CRM.url called before initialization');
19 }
8d83b77c
CW
20 if (!mode) {
21 mode = CRM.config.isFrontend ? 'front' : 'back';
22 }
53f2643c
CW
23 params = params || '';
24 var frag = p.split ('?');
8d83b77c 25 var url = tplURL[mode].replace("civicrm/example", frag[0]);
53f2643c
CW
26
27 if (typeof(params) == 'string') {
28 url = url.replace("placeholder", params);
29 }
30 else {
31 url = url.replace("placeholder", $.param(params));
32 }
33 if (frag[1]) {
34 url += (url.indexOf('?') === (url.length - 1) ? '' : '&') + frag[1];
35 }
36 // remove trailing "?"
37 if (url.indexOf('?') === (url.length - 1)) {
38 url = url.slice(0, (url.length - 1));
39 }
40 return url;
41 };
42
43 // Backwards compatible with jQuery fn
44 $.extend ({'crmURL':
45 function (p, params) {
46 console && console.log && console.log('Calling crmURL from jQuery is deprecated. Please use CRM.url() instead.');
47 return CRM.url(p, params);
48 }
49 });
50
51 $.fn.crmURL = function () {
52 return this.each(function() {
53 if (this.href) {
54 this.href = CRM.url(this.href);
55 }
56 });
57 };
58
59 /**
60 * AJAX api
61 */
62 CRM.api3 = function(entity, action, params, status) {
63 if (typeof(entity) === 'string') {
64 params = {
65 entity: entity,
66 action: action.toLowerCase(),
67 json: JSON.stringify(params || {})
68 };
69 } else {
70 params = {
71 entity: 'api3',
72 action: 'call',
73 json: JSON.stringify(entity)
e4f4dc22
CW
74 };
75 status = action;
53f2643c
CW
76 }
77 var ajax = $.ajax({
78 url: CRM.url('civicrm/ajax/rest'),
79 dataType: 'json',
80 data: params,
81 type: params.action.indexOf('get') < 0 ? 'POST' : 'GET'
82 });
83 if (status) {
84 // Default status messages
85 if (status === true) {
86 status = {success: params.action === 'delete' ? ts('Removed') : ts('Saved')};
87 if (params.action.indexOf('get') === 0) {
88 status.start = ts('Loading...');
89 status.success = null;
90 }
91 }
92 var messages = status === true ? {} : status;
93 CRM.status(status, ajax);
94 }
95 return ajax;
96 };
97
98 /**
99 * @deprecated
100 * AJAX api
101 */
102 CRM.api = function(entity, action, params, options) {
103 // Default settings
104 var settings = {
105 context: null,
106 success: function(result, settings) {
107 return true;
108 },
109 error: function(result, settings) {
110 $().crmError(result.error_message, ts('Error'));
111 return false;
112 },
113 callBack: function(result, settings) {
114 if (result.is_error == 1) {
115 return settings.error.call(this, result, settings);
116 }
117 return settings.success.call(this, result, settings);
118 },
119 ajaxURL: 'civicrm/ajax/rest'
120 };
121 action = action.toLowerCase();
122 // Default success handler
123 switch (action) {
124 case "update":
125 case "create":
126 case "setvalue":
127 case "replace":
128 settings.success = function() {
129 CRM.status(ts('Saved'));
130 return true;
131 };
132 break;
133 case "delete":
134 settings.success = function() {
135 CRM.status(ts('Removed'));
136 return true;
137 };
138 }
139 params = {
140 entity: entity,
141 action: action,
142 json: JSON.stringify(params)
143 };
144 // Pass copy of settings into closure to preserve its value during multiple requests
145 (function(stg) {
146 $.ajax({
147 url: stg.ajaxURL.indexOf('http') === 0 ? stg.ajaxURL : CRM.url(stg.ajaxURL),
148 dataType: 'json',
149 data: params,
150 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
151 success: function(result) {
152 stg.callBack.call(stg.context, result, stg);
153 }
154 });
155 })($.extend({}, settings, options));
156 };
157
158 /**
159 * Backwards compatible with jQuery fn
160 * @deprecated
161 */
162 $.fn.crmAPI = function(entity, action, params, options) {
163 console && console.log && console.log('Calling crmAPI from jQuery is deprecated. Please use CRM.api() instead.');
164 return CRM.api.call(this, entity, action, params, options);
165 };
166
167 $.widget('civi.crmSnippet', {
168 options: {
169 url: null,
170 block: true,
171 crmForm: null
172 },
173 _originalContent: null,
174 _originalUrl: null,
175 isOriginalUrl: function() {
176 var
177 args = {},
178 same = true,
179 newUrl = this._formatUrl(this.options.url),
180 oldUrl = this._formatUrl(this._originalUrl);
181 // Compare path
182 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
183 return false;
184 }
185 // Compare arguments
186 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
187 var arg = v.split('=');
188 args[arg[0]] = arg[1];
189 });
190 $.each(oldUrl.split('?')[1].split('&'), function(k, v) {
191 var arg = v.split('=');
192 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
193 same = false;
194 }
195 });
196 return same;
197 },
198 resetUrl: function() {
199 this.options.url = this._originalUrl;
200 },
201 _create: function() {
202 this.element.addClass('crm-ajax-container');
203 if (!this.element.is('.crm-container *')) {
204 this.element.addClass('crm-container');
205 }
206 this._handleOrderLinks();
207 // Set default if not supplied
208 this.options.url = this.options.url || document.location.href;
209 this._originalUrl = this.options.url;
210 },
211 _onFailure: function(data) {
212 this.options.block && this.element.unblock();
213 this.element.trigger('crmAjaxFail', data);
214 CRM.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
215 },
61cab70a
CW
216 _onError: function(data) {
217 this.element.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data);
f7aaf23c 218 if (this.options.crmForm && this.options.crmForm.autoClose && this.element.data('uiDialog')) {
61cab70a
CW
219 this.element.dialog('close');
220 }
221 },
53f2643c
CW
222 _formatUrl: function(url) {
223 // Strip hash
224 url = url.split('#')[0];
225 // Add snippet argument to url
226 if (url.search(/[&?]snippet=/) < 0) {
227 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
228 } else {
229 url = url.replace(/snippet=[^&]*/, 'snippet=json');
230 }
231 return url;
232 },
233 // Hack to deal with civicrm legacy sort functionality
234 _handleOrderLinks: function() {
235 var that = this;
236 $('a.crm-weight-arrow', that.element).click(function(e) {
237 that.options.block && that.element.block();
238 $.getJSON(that._formatUrl(this.href)).done(function() {
239 that.refresh();
240 });
241 e.stopImmediatePropagation();
242 return false;
243 });
244 },
245 refresh: function() {
246 var that = this;
247 var url = this._formatUrl(this.options.url);
248 this.options.crmForm && $('form', this.element).ajaxFormUnbind();
7e13d44e
CW
249 if (this._originalContent === null) {
250 this._originalContent = this.element.contents().detach();
251 }
53f2643c
CW
252 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
253 $.getJSON(url, function(data) {
61cab70a 254 if (!$.isPlainObject(data)) {
53f2643c
CW
255 that._onFailure(data);
256 return;
257 }
61cab70a
CW
258 if (data.status === 'error') {
259 that._onError(data);
260 return;
261 }
53f2643c 262 data.url = url;
7e13d44e 263 that.element.trigger('crmBeforeLoad', data).html(data.content);
53f2643c
CW
264 that._handleOrderLinks();
265 that.element.trigger('crmLoad', data);
266 that.options.crmForm && that.element.trigger('crmFormLoad', data);
267 }).fail(function() {
268 that._onFailure();
269 });
270 },
271 _destroy: function() {
272 this.element.removeClass('crm-ajax-container');
273 this.options.crmForm && $('form', this.element).ajaxFormUnbind();
274 if (this._originalContent !== null) {
275 this.element.empty().append(this._originalContent);
276 }
277 }
278 });
279
98465f9e
CW
280 var dialogCount = 0,
281 exclude = '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
282
53f2643c
CW
283 CRM.loadPage = function(url, options) {
284 var settings = {
285 target: '#crm-ajax-dialog-' + (dialogCount++),
286 dialog: false
287 };
288 if (!options || !options.target) {
289 settings.dialog = {
290 modal: true,
291 width: '65%',
292 height: '75%'
293 };
294 }
295 options && $.extend(true, settings, options);
296 settings.url = url;
297 // Create new dialog
298 if (settings.dialog) {
299 // HACK: jQuery UI doesn't support relative height
a1c7d42f 300 if (typeof settings.dialog.height === 'string' && settings.dialog.height.indexOf('%') > 0) {
53f2643c
CW
301 settings.dialog.height = parseInt($(window).height() * (parseFloat(settings.dialog.height)/100), 10);
302 }
303 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
73d2716e
CW
304 $(settings.target)
305 .on('dialogclose', function() {
306 if ($(this).attr('data-unsaved-changes') !== 'true') {
307 $(this).crmSnippet('destroy').dialog('destroy').remove();
308 }
309 })
310 .on('crmLoad', function(e, data) {
311 // Set title
312 if (e.target === $(settings.target)[0] && data && !settings.dialog.title && data.title) {
313 $(this).dialog('option', 'title', data.title);
314 }
315 // Adjust height to fit content (small delay to allow elements to render)
316 window.setTimeout(function() {
317 var currentHeight = $(settings.target).parent().height(),
318 padding = currentHeight - $(settings.target).height(),
319 newHeight = $(settings.target).prop('scrollHeight') + padding,
320 menuHeight = $('#civicrm-menu').height(),
321 maxHeight = $(window).height() - menuHeight;
322 newHeight = newHeight > maxHeight ? maxHeight : newHeight;
323 if (newHeight > (currentHeight + 15)) {
324 $(settings.target).dialog('option', {
325 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
326 height: newHeight
327 });
328 }
329 }, 500);
330 });
53f2643c
CW
331 }
332 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
333 return $(settings.target);
334 };
335 CRM.loadForm = function(url, options) {
55cb6db1 336 var formErrors = [], settings = {
53f2643c
CW
337 crmForm: {
338 ajaxForm: {},
339 autoClose: true,
340 validate: true,
02c82dda 341 refreshAction: ['next_new', 'submit_savenext', 'upload_new'],
98465f9e
CW
342 cancelButton: '.cancel',
343 openInline: 'a.open-inline, a.button, a.action-item',
1c1c1ae2 344 onCancel: function(event) {}
53f2643c
CW
345 }
346 };
347 // Move options that belong to crmForm. Others will be passed through to crmSnippet
348 options && $.each(options, function(key, value) {
349 if (typeof(settings.crmForm[key]) !== 'undefined') {
350 settings.crmForm[key] = value;
351 }
352 else {
353 settings[key] = value;
354 }
355 });
356
357 var widget = CRM.loadPage(url, settings).off('.crmForm');
358
f582fc8f 359 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
88e9380e 360 function cancelAction() {
e9a3e054 361 var dirty = CRM.utils.initialValueChanged($('form:not([data-warn-changes=false])', widget));
c4e00dbb 362 widget.attr('data-unsaved-changes', dirty ? 'true' : 'false');
7c2110fd
CW
363 if (dirty) {
364 var id = widget.attr('id') + '-unsaved-alert',
e9a3e054 365 title = widget.dialog('option', 'title'),
15d60951 366 alert = CRM.alert('<p>' + ts('%1 has not been saved.', {1: title}) + '</p><p><a href="#" id="' + id + '">' + ts('Restore') + '</a></p>', ts('Unsaved Changes'), 'alert unsaved-dialog', {expires: 60000});
8537b332 367 $('#' + id).button({icons: {primary: 'ui-icon-arrowreturnthick-1-w'}}).click(function(e) {
15d60951 368 widget.attr('data-unsaved-changes', 'false').dialog('open');
8537b332 369 e.preventDefault();
7c2110fd 370 });
88e9380e 371 }
88e9380e 372 }
c4e00dbb
CW
373
374 widget.data('uiDialog') && widget.on('dialogbeforeclose', function(e) {
375 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
376 if (e.originalEvent) {
377 cancelAction();
378 }
379 });
88e9380e 380
53f2643c 381 widget.on('crmFormLoad.crmForm', function(event, data) {
7c2110fd 382 var $el = $(this)
15d60951 383 .attr('data-unsaved-changes', 'false');
53f2643c 384 var settings = $el.crmSnippet('option', 'crmForm');
7c2110fd
CW
385 settings.cancelButton && $(settings.cancelButton, this).click(function(e) {
386 e.preventDefault();
387 var returnVal = settings.onCancel.call($el, e);
53f2643c 388 if (returnVal !== false) {
7c2110fd 389 $el.trigger('crmFormCancel', e);
53f2643c 390 if ($el.data('uiDialog') && settings.autoClose) {
7c2110fd 391 cancelAction();
c4e00dbb 392 $el.dialog('close');
53f2643c
CW
393 }
394 else if (!settings.autoClose) {
395 $el.crmSnippet('resetUrl').crmSnippet('refresh');
396 }
397 }
53f2643c
CW
398 });
399 if (settings.validate) {
3d527838 400 $("form", this).crmValidate();
53f2643c 401 }
cae80d9f 402 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
53f2643c
CW
403 url: data.url.replace(/reset=1[&]?/, ''),
404 dataType: 'json',
405 success: function(response) {
1c1c1ae2 406 if (response.content === undefined) {
53f2643c
CW
407 $el.crmSnippet('option', 'block') && $el.unblock();
408 $el.trigger('crmFormSuccess', response);
409 // Reset form for e.g. "save and new"
0a94ab7d 410 if (response.userContext && (response.status === 'redirect' || (settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0))) {
b305fb88
CW
411 // Force reset of original url
412 $el.data('civiCrmSnippet')._originalUrl = response.userContext;
413 $el.crmSnippet('resetUrl').crmSnippet('refresh');
53f2643c 414 }
9317128c
CW
415 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
416 else if ($el.data('uiDialog') && (settings.autoClose || response.action === 8)) {
53f2643c
CW
417 $el.dialog('close');
418 }
419 else if (settings.autoClose === false) {
420 $el.crmSnippet('resetUrl').crmSnippet('refresh');
421 }
422 }
423 else {
424 response.url = data.url;
1c1c1ae2
CW
425 $el.html(response.content).trigger('crmLoad', response).trigger('crmFormLoad', response);
426 if (response.status === 'form_error') {
55cb6db1 427 formErrors = [];
1c1c1ae2
CW
428 $el.trigger('crmFormError', response);
429 $.each(response.errors || [], function(formElement, msg) {
55cb6db1 430 formErrors.push($('[name="'+formElement+'"]', $el).crmError(msg));
1c1c1ae2
CW
431 });
432 }
53f2643c
CW
433 }
434 },
435 beforeSerialize: function(form, options) {
436 if (window.CKEDITOR && window.CKEDITOR.instances) {
437 $.each(CKEDITOR.instances, function() {
438 this.updateElement && this.updateElement();
439 });
440 }
441 },
442 beforeSubmit: function(submission) {
55cb6db1
CW
443 $.each(formErrors, function() {
444 this && this.close && this.close();
445 });
53f2643c
CW
446 $el.crmSnippet('option', 'block') && $el.block();
447 $el.trigger('crmFormSubmit', submission);
448 }
449 }, settings.ajaxForm));
450 if (settings.openInline) {
451 settings.autoClose = $el.crmSnippet('isOriginalUrl');
98465f9e 452 $(settings.openInline, this).not(exclude + ', .crm-popup').click(function(event) {
53f2643c
CW
453 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
454 return false;
455 });
456 }
022d2163 457 // Allow a button to prevent ajax submit
1e29624c
CW
458 $('input[data-no-ajax-submit=true]').click(function() {
459 $(this).closest('form').ajaxFormUnbind();
460 });
53f2643c 461 // For convenience, focus the first field
b18392cc 462 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
53f2643c
CW
463 });
464 return widget;
465 };
466 /**
022d2163 467 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
53f2643c 468 */
35df910c 469 CRM.popup = function(e) {
53f2643c
CW
470 var $el = $(this).first(),
471 url = $el.attr('href'),
472 popup = $el.data('popup-type') === 'page' ? CRM.loadPage : CRM.loadForm,
473 settings = $el.data('popup-settings') || {},
7fe745d1 474 formSuccess = false;
53f2643c 475 settings.dialog = settings.dialog || {};
35df910c 476 if (e.isDefaultPrevented() || !CRM.config.ajaxPopupsEnabled || !url || $el.is(exclude)) {
53f2643c
CW
477 return;
478 }
a1c7d42f
CW
479 // Sized based on css class
480 if ($el.hasClass('small-popup')) {
53f2643c
CW
481 settings.dialog.width = 400;
482 settings.dialog.height = 300;
483 }
484 else if ($el.hasClass('medium-popup')) {
485 settings.dialog.width = settings.dialog.height = '50%';
486 }
487 else if ($el.hasClass('huge-popup')) {
77042884 488 settings.dialog.height = '90%';
53f2643c
CW
489 }
490 var dialog = popup(url, settings);
491 // Trigger events from the dialog on the original link element
492 $el.trigger('crmPopupOpen', [dialog]);
4b472ff2
CW
493 // Listen for success events and buffer them so we only trigger once
494 dialog.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
7fe745d1
CW
495 formSuccess = true;
496 });
497 dialog.on('dialogclose.crmPopup', function(e, data) {
498 if (formSuccess) {
499 $el.trigger('crmPopupFormSuccess', [dialog, data]);
500 }
501 $el.trigger('crmPopupClose', [dialog, data]);
53f2643c 502 });
35df910c 503 e.preventDefault();
53f2643c 504 };
554b1768 505 /**
7e9fdecf 506 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
022d2163 507 * @param e {event|selector}
554b1768
CW
508 */
509 CRM.refreshParent = function(e) {
510 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
511 var $el = (e.stopPropagation && e.target) ? $(e.target) : $(e),
512 $table = $el.closest('.dataTable');
513 // Call native refresh method on ajax datatables
022d2163 514 if ($table.length && $.fn.DataTable.fnIsDataTable($table[0]) && $table.dataTable().fnSettings().sAjaxSource) {
554b1768
CW
515 // Refresh ALL datatables - needed for contact relationship tab
516 $.each($.fn.dataTable.fnTables(), function() {
517 $(this).dataTable().fnSettings().sAjaxSource && $(this).unblock().dataTable().fnDraw();
518 });
519 }
520 // Otherwise refresh the nearest crmSnippet
521 else {
522 $el.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
523 }
524 };
a1c7d42f
CW
525
526 $(function($) {
15d60951
CW
527 $('body')
528 .on('click', 'a.crm-popup', CRM.popup)
529 // Close unsaved dialog messages
530 .on('dialogopen', function(e) {
531 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
532 })
533 // Destroy old unsaved dialog
534 .on('dialogcreate', function(e) {
535 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
536 });
a1c7d42f
CW
537 });
538
53f2643c 539}(jQuery, CRM));