1 // https://civicrm.org/licensing
3 * @see https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
4 * @see https://docs.civicrm.org/dev/en/latest/framework/ajax/
6 (function($, CRM
, _
, undefined) {
9 * @param string|object query
10 * @param string mode - optionally specify "front" or "back"
13 CRM
.url = function (path
, query
, mode
) {
14 if (typeof path
=== 'object') {
19 CRM
.console('error', 'Error: CRM.url called before initialization');
22 mode
= CRM
.config
&& CRM
.config
.isFrontend
? 'front' : 'back';
25 var url
, frag
, hash
= '';
26 if (path
.indexOf('#') > -1) {
27 hash
= '#' + path
.split('#')[1];
28 path
= path
.split('#')[0];
30 frag
= path
.split('?');
31 // Encode url path only if slashes in placeholder were also encoded
32 if (tplURL
[mode
].indexOf('civicrm/placeholder-url-path') >= 0) {
33 url
= tplURL
[mode
].replace('civicrm/placeholder-url-path', frag
[0]);
35 url
= tplURL
[mode
].replace('civicrm%2Fplaceholder-url-path', encodeURIComponent(frag
[0]));
38 if (_
.isEmpty(query
)) {
39 url
= url
.replace(/[?&]civicrm-placeholder-url-query=1/, '');
41 url
= url
.replace('civicrm-placeholder-url-query=1', typeof query
=== 'string' ? query
: $.param(query
));
44 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + frag
[1];
49 $.fn
.crmURL = function () {
50 return this.each(function() {
52 this.href
= CRM
.url(this.href
);
57 // result is an array, but in js, an array is also an object
58 // Assign all the metadata properties to it, mirroring the results arrayObject in php
59 function arrayObject(data
) {
60 var result
= data
.values
|| [];
61 if (_
.isArray(result
)) {
63 _
.assign(result
, data
);
68 // https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
69 CRM
.api4 = function(entity
, action
, params
, index
) {
70 return new Promise(function(resolve
, reject
) {
71 if (typeof entity
=== 'string') {
72 $.post(CRM
.url('civicrm/ajax/api4/' + entity
+ '/' + action
), {
73 params
: JSON
.stringify(params
),
76 .done(function (data
) {
77 resolve(arrayObject(data
));
79 .fail(function (data
) {
80 reject(data
.responseJSON
);
83 $.post(CRM
.url('civicrm/ajax/api4'), {
84 calls
: JSON
.stringify(entity
)
86 .done(function(data
) {
87 _
.each(data
, function(item
, key
) {
88 data
[key
] = arrayObject(item
);
92 .fail(function (data
) {
93 reject(data
.responseJSON
);
101 * @link https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
103 CRM
.api3 = function(entity
, action
, params
, status
) {
104 if (typeof(entity
) === 'string') {
107 action
: action
.toLowerCase(),
108 json
: JSON
.stringify(params
|| {})
114 json
: JSON
.stringify(entity
)
119 url
: CRM
.url('civicrm/ajax/rest'),
122 type
: params
.action
.indexOf('get') === 0 ? 'GET' : 'POST'
125 // Default status messages
126 if (status
=== true) {
127 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
128 if (params
.action
.indexOf('get') === 0) {
129 status
.start
= ts('Loading...');
130 status
.success
= null;
133 var messages
= status
=== true ? {} : status
;
134 CRM
.status(status
, ajax
);
143 CRM
.api = function(entity
, action
, params
, options
) {
147 success: function(result
, settings
) {
150 error: function(result
, settings
) {
151 $().crmError(result
.error_message
, ts('Error'));
154 callBack: function(result
, settings
) {
155 if (result
.is_error
== 1) {
156 return settings
.error
.call(this, result
, settings
);
158 return settings
.success
.call(this, result
, settings
);
160 ajaxURL
: 'civicrm/ajax/rest'
162 action
= action
.toLowerCase();
163 // Default success handler
169 settings
.success = function() {
170 CRM
.status(ts('Saved'));
175 settings
.success = function() {
176 CRM
.status(ts('Removed'));
183 json
: JSON
.stringify(params
)
185 // Pass copy of settings into closure to preserve its value during multiple requests
188 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
191 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
192 success: function(result
) {
193 stg
.callBack
.call(stg
.context
, result
, stg
);
196 })($.extend({}, settings
, options
));
199 $.widget('civi.crmSnippet', {
205 _originalContent
: null,
207 isOriginalUrl: function() {
211 newUrl
= this._formatUrl(this.options
.url
),
212 oldUrl
= this._formatUrl(this._originalUrl
);
214 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
218 $.each((newUrl
.split('?')[1] || '').split('&'), function(k
, v
) {
219 var arg
= v
.split('=');
220 args
[arg
[0]] = arg
[1];
222 $.each((oldUrl
.split('?')[1] || '').split('&'), function(k
, v
) {
223 var arg
= v
.split('=');
224 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
230 resetUrl: function() {
231 this.options
.url
= this._originalUrl
;
233 _create: function() {
234 this.element
.addClass('crm-ajax-container');
235 if (!this.element
.is('.crm-container *')) {
236 this.element
.addClass('crm-container');
238 this._handleOrderLinks();
239 // Set default if not supplied
240 this.options
.url
= this.options
.url
|| document
.location
.href
;
241 this._originalUrl
= this.options
.url
;
243 _onFailure: function(data
, status
) {
244 var msg
, title
= ts('Network Error');
245 if (this.options
.block
) this.element
.unblock();
246 this.element
.trigger('crmAjaxFail', data
);
249 title
= ts('Access Denied');
250 msg
= ts('Ensure you are still logged in and have permission to access this feature.');
253 msg
= ts('Unable to reach the server. Please refresh this page in your browser and try again.');
255 CRM
.alert(msg
, title
, 'error');
257 _onError: function(data
) {
258 this.element
.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data
);
259 if (this.options
.crmForm
&& this.options
.crmForm
.autoClose
&& this.element
.data('uiDialog')) {
260 this.element
.dialog('close');
263 _formatUrl: function(url
, snippetType
) {
265 url
= url
.split('#')[0];
266 // Add snippet argument to url
268 if (url
.search(/[&?]snippet=/) < 0) {
269 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=' + snippetType
;
271 url
= url
.replace(/snippet=[^&]*/, 'snippet=' + snippetType
);
276 // Hack to deal with civicrm legacy sort functionality
277 _handleOrderLinks: function() {
279 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
280 if (that
.options
.block
) that
.element
.block();
281 $.getJSON(that
._formatUrl(this.href
, 'json')).done(function() {
284 e
.stopImmediatePropagation();
288 refresh: function() {
290 var url
= this._formatUrl(this.options
.url
, 'json');
291 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
292 if (this.options
.block
) this.element
.block();
293 $.getJSON(url
, function(data
) {
294 if (data
.status
=== 'redirect') {
295 that
.options
.url
= data
.userContext
;
296 return that
.refresh();
298 if (that
.options
.block
) that
.element
.unblock();
299 if (!$.isPlainObject(data
)) {
300 that
._onFailure(data
);
303 if (data
.status
=== 'error') {
308 that
.element
.trigger('crmUnload').trigger('crmBeforeLoad', data
);
309 that
._beforeRemovingContent();
310 that
.element
.html(data
.content
);
311 that
._handleOrderLinks();
312 that
.element
.trigger('crmLoad', data
);
313 if (that
.options
.crmForm
) that
.element
.trigger('crmFormLoad', data
);
314 // This is only needed by forms that load via ajax but submit without ajax, e.g. configure contribution page tabs
315 // TODO: remove this when those forms have been converted to use ajax submit
316 if (data
.status
=== 'form_error' && $.isPlainObject(data
.errors
)) {
317 that
.element
.trigger('crmFormError', data
);
318 $.each(data
.errors
, function(formElement
, msg
) {
319 $('[name="'+formElement
+'"]', that
.element
).crmError(msg
);
322 }).fail(function(data
, msg
, status
) {
323 that
._onFailure(data
, status
);
326 // Perform any cleanup needed before removing/replacing content
327 _beforeRemovingContent: function() {
329 // Save original content to be restored if widget is destroyed
330 if (this._originalContent
=== null) {
331 $('.blockUI', this.element
).remove();
332 this._originalContent
= this.element
.contents().detach();
334 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
336 _destroy: function() {
337 this.element
.removeClass('crm-ajax-container').trigger('crmUnload');
338 this._beforeRemovingContent();
339 if (this._originalContent
!== null) {
340 this.element
.empty().append(this._originalContent
);
346 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
348 CRM
.loadPage = function(url
, options
) {
350 target
: '#crm-ajax-dialog-' + (dialogCount
++),
351 dialog
: (options
&& options
.target
) ? false : {}
353 if (options
) $.extend(true, settings
, options
);
356 if (settings
.dialog
) {
357 settings
.dialog
= CRM
.utils
.adjustDialogDefaults(settings
.dialog
);
358 $('<div id="' + settings
.target
.substring(1) + '"></div>')
359 .dialog(settings
.dialog
)
360 .parent().find('.ui-dialog-titlebar')
361 .append($('<a class="crm-dialog-titlebar-print ui-dialog-titlebar-close" title="'+ts('Print window')+'" target="_blank" style="right:3.8em;"/>')
362 .button({icons
: {primary
: 'fa-print'}, text
: false}));
364 // Add handlers to new or existing dialog
365 if ($(settings
.target
).data('uiDialog')) {
367 .on('dialogclose', function() {
368 if (settings
.dialog
&& $(this).attr('data-unsaved-changes') !== 'true') {
369 $(this).crmSnippet('destroy').dialog('destroy').remove();
372 .on('crmLoad', function(e
, data
) {
374 if (e
.target
=== $(settings
.target
)[0] && data
&& !settings
.dialog
.title
&& data
.title
) {
375 $(this).dialog('option', 'title', data
.title
);
378 $(this).parent().find('a.crm-dialog-titlebar-print').attr('href', $(this).data('civiCrmSnippet')._formatUrl($(this).crmSnippet('option', 'url'), '2'));
381 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
382 return $(settings
.target
);
384 CRM
.loadForm = function(url
, options
) {
385 var formErrors
= [], settings
= {
390 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
391 cancelButton
: '.cancel',
392 openInline
: 'a.open-inline, a.button, a.action-item, a.open-inline-noreturn',
393 onCancel: function(event
) {}
396 // Move options that belong to crmForm. Others will be passed through to crmSnippet
397 if (options
) $.each(options
, function(key
, value
) {
398 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
399 settings
.crmForm
[key
] = value
;
402 settings
[key
] = value
;
406 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
408 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
409 function cancelAction() {
410 var dirty
= CRM
.utils
.initialValueChanged($('form:not([data-warn-changes=false])', widget
));
411 widget
.attr('data-unsaved-changes', dirty
? 'true' : 'false');
413 var id
= widget
.attr('id') + '-unsaved-alert',
414 title
= widget
.dialog('option', 'title'),
415 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});
416 $('#' + id
).button({icons
: {primary
: 'fa-undo'}}).click(function(e
) {
417 widget
.attr('data-unsaved-changes', 'false').dialog('open');
423 if (widget
.data('uiDialog')) widget
.on('dialogbeforeclose', function(e
) {
424 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
425 if (e
.originalEvent
) {
430 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
431 var $el
= $(this).attr('data-unsaved-changes', 'false'),
432 settings
= $el
.crmSnippet('option', 'crmForm');
433 if (settings
.cancelButton
) $(settings
.cancelButton
, this).click(function(e
) {
435 var returnVal
= settings
.onCancel
.call($el
, e
);
436 if (returnVal
!== false) {
437 $el
.trigger('crmFormCancel', e
);
438 if ($el
.data('uiDialog') && settings
.autoClose
) {
442 else if (!settings
.autoClose
) {
443 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
447 if (settings
.validate
) {
448 $("form", this).crmValidate();
450 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
451 url
: data
.url
.replace(/reset=1[&]?/, ''),
453 success: function(response
) {
454 if (response
.content
=== undefined) {
455 $el
.trigger('crmFormSuccess', response
);
456 // Reset form for e.g. "save and new"
457 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
458 // Force reset of original url
459 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
460 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
462 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
463 else if ($el
.data('uiDialog') && (settings
.autoClose
|| response
.action
=== 8)) {
466 else if (settings
.autoClose
=== false) {
467 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
471 if ($el
.crmSnippet('option', 'block')) $el
.unblock();
472 response
.url
= data
.url
;
473 $el
.html(response
.content
).trigger('crmLoad', response
).trigger('crmFormLoad', response
);
474 if (response
.status
=== 'form_error') {
476 $el
.trigger('crmFormError', response
);
477 $.each(response
.errors
|| [], function(formElement
, msg
) {
478 formErrors
.push($('[name="'+formElement
+'"]', $el
).crmError(msg
));
483 beforeSubmit: function(submission
) {
484 $.each(formErrors
, function() {
485 if (this && this.close
) this.close();
487 if ($el
.crmSnippet('option', 'block')) $el
.block();
488 $el
.trigger('crmFormSubmit', submission
);
490 }, settings
.ajaxForm
));
491 if (settings
.openInline
) {
492 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
493 $(this).off('.openInline').on('click.openInline', settings
.openInline
, function(e
) {
494 if ($(this).is(exclude
+ ', .crm-popup, [target=crm-popup]')) {
497 if ($(this).hasClass('open-inline-noreturn')) {
498 // Force reset of original url
499 $el
.data('civiCrmSnippet')._originalUrl
= $(this).attr('href');
501 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
505 if ($el
.data('uiDialog')) {
506 // Show form buttons as part of the dialog
507 var buttonContainers
= '.crm-submit-buttons, .action-link',
510 $(buttonContainers
, $el
).find('.crm-form-submit, .crm-form-xbutton, a.button, button').each(function() {
512 label
= $el
.is('input') ? $el
.attr('value') : $el
.text(),
513 identifier
= $el
.attr('name') || $el
.attr('href');
514 $el
.attr('tabindex', '-1');
515 if (!identifier
|| identifier
=== '#' || $.inArray(identifier
, added
) < 0) {
516 var $icon
= $el
.find('.icon, .crm-i'),
517 button
= {'data-identifier': identifier
, text
: label
, click: function() {
521 button
.icons
= {primary
: $icon
.attr('class')};
523 var action
= $el
.attr('crm-icon') || ($el
.hasClass('cancel') ? 'fa-times' : 'fa-check');
524 button
.icons
= {primary
: action
};
526 buttons
.push(button
);
527 added
.push(identifier
);
529 // display:none causes the form to not submit when pressing "enter"
530 $el
.parents(buttonContainers
).css({height
: 0, padding
: 0, margin
: 0, overflow
: 'hidden'}).attr('aria-hidden', 'true');
532 $el
.dialog('option', 'buttons', buttons
);
534 // Allow a button to prevent ajax submit
535 $('input[data-no-ajax-submit=true], button[data-no-ajax-submit=true]').click(function() {
536 $(this).closest('form').ajaxFormUnbind();
538 // For convenience, focus the first field
539 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
544 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
546 CRM
.popup = function(e
) {
547 var $el
= $(this).first(),
548 url
= $el
.attr('href'),
549 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
550 settings
= $el
.data('popup-settings') || {},
552 settings
.dialog
= settings
.dialog
|| {};
553 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
+ ', .open-inline, .open-inline-noreturn')) {
556 // Sized based on css class
557 if ($el
.hasClass('small-popup')) {
558 settings
.dialog
.width
= 400;
559 settings
.dialog
.height
= 300;
561 else if ($el
.hasClass('medium-popup')) {
562 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
564 var dialog
= popup(url
, settings
);
565 // Trigger events from the dialog on the original link element
566 $el
.trigger('crmPopupOpen', [dialog
]);
567 // Listen for success events and buffer them so we only trigger once
568 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function(e
, data
) {
571 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
573 $el
.trigger('crmPopupFormSuccess', [dialog
, formData
]);
575 $el
.trigger('crmPopupClose', [dialog
, data
]);
580 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
581 * @param e {event|selector}
583 CRM
.refreshParent = function(e
) {
584 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
585 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
586 $table
= $el
.closest('.dataTable');
587 // Call native refresh method on ajax datatables
588 if ($table
.length
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
589 // Refresh ALL datatables - needed for contact relationship tab
590 $.each($.fn
.dataTable
.fnTables(), function() {
591 if ($(this).dataTable().fnSettings().sAjaxSource
) $(this).unblock().dataTable().fnDraw();
594 // Otherwise refresh the nearest crmSnippet
596 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
602 .on('click', 'a.crm-popup, a[target=crm-popup]', CRM
.popup
)
603 // Close unsaved dialog messages
604 .on('dialogopen', function(e
) {
605 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
607 // Destroy old unsaved dialog
608 .on('dialogcreate', function(e
) {
609 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
611 // Ensure wysiwyg content is updated prior to ajax submit
612 .on('form-pre-serialize', function(e
) {
613 $('.crm-wysiwyg-enabled', e
.target
).each(function() {
614 CRM
.wysiwyg
.updateElement(this);
617 // Auto-resize dialogs when loading content
618 .on('crmLoad dialogopen', 'div.ui-dialog.ui-resizable.crm-container', function(e
) {
621 $dialog
= $wrapper
.children('.ui-dialog-content');
622 // small delay to allow contents to render
623 window
.setTimeout(function() {
624 var currentHeight
= $wrapper
.outerHeight(),
625 padding
= currentHeight
- $dialog
.height(),
626 newHeight
= $dialog
.prop('scrollHeight') + padding
,
627 menuHeight
= $('#civicrm-menu').outerHeight();
628 if ($('body').hasClass('crm-menubar-below-cms-menu')) {
629 menuHeight
+= $('#civicrm-menu').offset().top
;
631 var maxHeight
= $(window
).height() - menuHeight
;
632 newHeight
= newHeight
> maxHeight
? maxHeight
: newHeight
;
633 if (newHeight
> (currentHeight
+ 15)) {
634 $dialog
.dialog('option', {
635 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},