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 frag
= path
.split('?');
26 var url
= tplURL
[mode
].replace("civicrm-placeholder-url-path", frag
[0]);
29 url
= url
.replace(/[?&]civicrm-placeholder-url-query=1/, '');
32 url
= url
.replace("civicrm-placeholder-url-query=1", typeof query
=== 'string' ? query
: $.param(query
));
35 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + frag
[1];
40 $.fn
.crmURL = function () {
41 return this.each(function() {
43 this.href
= CRM
.url(this.href
);
48 // result is an array, but in js, an array is also an object
49 // Assign all the metadata properties to it, mirroring the results arrayObject in php
50 function arrayObject(data
) {
51 var result
= data
.values
|| [];
52 if (_
.isArray(result
)) {
54 _
.assign(result
, data
);
59 // https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
60 CRM
.api4 = function(entity
, action
, params
, index
) {
61 return new Promise(function(resolve
, reject
) {
62 if (typeof entity
=== 'string') {
63 $.post(CRM
.url('civicrm/ajax/api4/' + entity
+ '/' + action
), {
64 params
: JSON
.stringify(params
),
67 .done(function (data
) {
68 resolve(arrayObject(data
));
70 .fail(function (data
) {
71 reject(data
.responseJSON
);
74 $.post(CRM
.url('civicrm/ajax/api4'), {
75 calls
: JSON
.stringify(entity
)
77 .done(function(data
) {
78 _
.each(data
, function(item
, key
) {
79 data
[key
] = arrayObject(item
);
83 .fail(function (data
) {
84 reject(data
.responseJSON
);
92 * @link https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
94 CRM
.api3 = function(entity
, action
, params
, status
) {
95 if (typeof(entity
) === 'string') {
98 action
: action
.toLowerCase(),
99 json
: JSON
.stringify(params
|| {})
105 json
: JSON
.stringify(entity
)
110 url
: CRM
.url('civicrm/ajax/rest'),
113 type
: params
.action
.indexOf('get') === 0 ? 'GET' : 'POST'
116 // Default status messages
117 if (status
=== true) {
118 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
119 if (params
.action
.indexOf('get') === 0) {
120 status
.start
= ts('Loading...');
121 status
.success
= null;
124 var messages
= status
=== true ? {} : status
;
125 CRM
.status(status
, ajax
);
134 CRM
.api = function(entity
, action
, params
, options
) {
138 success: function(result
, settings
) {
141 error: function(result
, settings
) {
142 $().crmError(result
.error_message
, ts('Error'));
145 callBack: function(result
, settings
) {
146 if (result
.is_error
== 1) {
147 return settings
.error
.call(this, result
, settings
);
149 return settings
.success
.call(this, result
, settings
);
151 ajaxURL
: 'civicrm/ajax/rest'
153 action
= action
.toLowerCase();
154 // Default success handler
160 settings
.success = function() {
161 CRM
.status(ts('Saved'));
166 settings
.success = function() {
167 CRM
.status(ts('Removed'));
174 json
: JSON
.stringify(params
)
176 // Pass copy of settings into closure to preserve its value during multiple requests
179 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
182 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
183 success: function(result
) {
184 stg
.callBack
.call(stg
.context
, result
, stg
);
187 })($.extend({}, settings
, options
));
190 $.widget('civi.crmSnippet', {
196 _originalContent
: null,
198 isOriginalUrl: function() {
202 newUrl
= this._formatUrl(this.options
.url
),
203 oldUrl
= this._formatUrl(this._originalUrl
);
205 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
209 $.each((newUrl
.split('?')[1] || '').split('&'), function(k
, v
) {
210 var arg
= v
.split('=');
211 args
[arg
[0]] = arg
[1];
213 $.each((oldUrl
.split('?')[1] || '').split('&'), function(k
, v
) {
214 var arg
= v
.split('=');
215 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
221 resetUrl: function() {
222 this.options
.url
= this._originalUrl
;
224 _create: function() {
225 this.element
.addClass('crm-ajax-container');
226 if (!this.element
.is('.crm-container *')) {
227 this.element
.addClass('crm-container');
229 this._handleOrderLinks();
230 // Set default if not supplied
231 this.options
.url
= this.options
.url
|| document
.location
.href
;
232 this._originalUrl
= this.options
.url
;
234 _onFailure: function(data
, status
) {
235 var msg
, title
= ts('Network Error');
236 if (this.options
.block
) this.element
.unblock();
237 this.element
.trigger('crmAjaxFail', data
);
240 title
= ts('Access Denied');
241 msg
= ts('Ensure you are still logged in and have permission to access this feature.');
244 msg
= ts('Unable to reach the server. Please refresh this page in your browser and try again.');
246 CRM
.alert(msg
, title
, 'error');
248 _onError: function(data
) {
249 this.element
.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data
);
250 if (this.options
.crmForm
&& this.options
.crmForm
.autoClose
&& this.element
.data('uiDialog')) {
251 this.element
.dialog('close');
254 _formatUrl: function(url
, snippetType
) {
256 url
= url
.split('#')[0];
257 // Add snippet argument to url
259 if (url
.search(/[&?]snippet=/) < 0) {
260 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=' + snippetType
;
262 url
= url
.replace(/snippet=[^&]*/, 'snippet=' + snippetType
);
267 // Hack to deal with civicrm legacy sort functionality
268 _handleOrderLinks: function() {
270 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
271 if (that
.options
.block
) that
.element
.block();
272 $.getJSON(that
._formatUrl(this.href
, 'json')).done(function() {
275 e
.stopImmediatePropagation();
279 refresh: function() {
281 var url
= this._formatUrl(this.options
.url
, 'json');
282 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
283 if (this.options
.block
) this.element
.block();
284 $.getJSON(url
, function(data
) {
285 if (data
.status
=== 'redirect') {
286 that
.options
.url
= data
.userContext
;
287 return that
.refresh();
289 if (that
.options
.block
) that
.element
.unblock();
290 if (!$.isPlainObject(data
)) {
291 that
._onFailure(data
);
294 if (data
.status
=== 'error') {
299 that
.element
.trigger('crmUnload').trigger('crmBeforeLoad', data
);
300 that
._beforeRemovingContent();
301 that
.element
.html(data
.content
);
302 that
._handleOrderLinks();
303 that
.element
.trigger('crmLoad', data
);
304 if (that
.options
.crmForm
) that
.element
.trigger('crmFormLoad', data
);
305 // This is only needed by forms that load via ajax but submit without ajax, e.g. configure contribution page tabs
306 // TODO: remove this when those forms have been converted to use ajax submit
307 if (data
.status
=== 'form_error' && $.isPlainObject(data
.errors
)) {
308 that
.element
.trigger('crmFormError', data
);
309 $.each(data
.errors
, function(formElement
, msg
) {
310 $('[name="'+formElement
+'"]', that
.element
).crmError(msg
);
313 }).fail(function(data
, msg
, status
) {
314 that
._onFailure(data
, status
);
317 // Perform any cleanup needed before removing/replacing content
318 _beforeRemovingContent: function() {
320 // Save original content to be restored if widget is destroyed
321 if (this._originalContent
=== null) {
322 $('.blockUI', this.element
).remove();
323 this._originalContent
= this.element
.contents().detach();
325 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
327 _destroy: function() {
328 this.element
.removeClass('crm-ajax-container').trigger('crmUnload');
329 this._beforeRemovingContent();
330 if (this._originalContent
!== null) {
331 this.element
.empty().append(this._originalContent
);
337 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
339 CRM
.loadPage = function(url
, options
) {
341 target
: '#crm-ajax-dialog-' + (dialogCount
++),
342 dialog
: (options
&& options
.target
) ? false : {}
344 if (options
) $.extend(true, settings
, options
);
347 if (settings
.dialog
) {
348 settings
.dialog
= CRM
.utils
.adjustDialogDefaults(settings
.dialog
);
349 $('<div id="' + settings
.target
.substring(1) + '"></div>')
350 .dialog(settings
.dialog
)
351 .parent().find('.ui-dialog-titlebar')
352 .append($('<a class="crm-dialog-titlebar-print ui-dialog-titlebar-close" title="'+ts('Print window')+'" target="_blank" style="right:3.8em;"/>')
353 .button({icons
: {primary
: 'fa-print'}, text
: false}));
355 // Add handlers to new or existing dialog
356 if ($(settings
.target
).data('uiDialog')) {
358 .on('dialogclose', function() {
359 if (settings
.dialog
&& $(this).attr('data-unsaved-changes') !== 'true') {
360 $(this).crmSnippet('destroy').dialog('destroy').remove();
363 .on('crmLoad', function(e
, data
) {
365 if (e
.target
=== $(settings
.target
)[0] && data
&& !settings
.dialog
.title
&& data
.title
) {
366 $(this).dialog('option', 'title', data
.title
);
369 $(this).parent().find('a.crm-dialog-titlebar-print').attr('href', $(this).data('civiCrmSnippet')._formatUrl($(this).crmSnippet('option', 'url'), '2'));
372 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
373 return $(settings
.target
);
375 CRM
.loadForm = function(url
, options
) {
376 var formErrors
= [], settings
= {
381 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
382 cancelButton
: '.cancel',
383 openInline
: 'a.open-inline, a.button, a.action-item, a.open-inline-noreturn',
384 onCancel: function(event
) {}
387 // Move options that belong to crmForm. Others will be passed through to crmSnippet
388 if (options
) $.each(options
, function(key
, value
) {
389 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
390 settings
.crmForm
[key
] = value
;
393 settings
[key
] = value
;
397 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
399 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
400 function cancelAction() {
401 var dirty
= CRM
.utils
.initialValueChanged($('form:not([data-warn-changes=false])', widget
));
402 widget
.attr('data-unsaved-changes', dirty
? 'true' : 'false');
404 var id
= widget
.attr('id') + '-unsaved-alert',
405 title
= widget
.dialog('option', 'title'),
406 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});
407 $('#' + id
).button({icons
: {primary
: 'fa-undo'}}).click(function(e
) {
408 widget
.attr('data-unsaved-changes', 'false').dialog('open');
414 if (widget
.data('uiDialog')) widget
.on('dialogbeforeclose', function(e
) {
415 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
416 if (e
.originalEvent
) {
421 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
422 var $el
= $(this).attr('data-unsaved-changes', 'false'),
423 settings
= $el
.crmSnippet('option', 'crmForm');
424 if (settings
.cancelButton
) $(settings
.cancelButton
, this).click(function(e
) {
426 var returnVal
= settings
.onCancel
.call($el
, e
);
427 if (returnVal
!== false) {
428 $el
.trigger('crmFormCancel', e
);
429 if ($el
.data('uiDialog') && settings
.autoClose
) {
433 else if (!settings
.autoClose
) {
434 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
438 if (settings
.validate
) {
439 $("form", this).crmValidate();
441 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
442 url
: data
.url
.replace(/reset=1[&]?/, ''),
444 success: function(response
) {
445 if (response
.content
=== undefined) {
446 $el
.trigger('crmFormSuccess', response
);
447 // Reset form for e.g. "save and new"
448 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
449 // Force reset of original url
450 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
451 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
453 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
454 else if ($el
.data('uiDialog') && (settings
.autoClose
|| response
.action
=== 8)) {
457 else if (settings
.autoClose
=== false) {
458 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
462 if ($el
.crmSnippet('option', 'block')) $el
.unblock();
463 response
.url
= data
.url
;
464 $el
.html(response
.content
).trigger('crmLoad', response
).trigger('crmFormLoad', response
);
465 if (response
.status
=== 'form_error') {
467 $el
.trigger('crmFormError', response
);
468 $.each(response
.errors
|| [], function(formElement
, msg
) {
469 formErrors
.push($('[name="'+formElement
+'"]', $el
).crmError(msg
));
474 beforeSubmit: function(submission
) {
475 $.each(formErrors
, function() {
476 if (this && this.close
) this.close();
478 if ($el
.crmSnippet('option', 'block')) $el
.block();
479 $el
.trigger('crmFormSubmit', submission
);
481 }, settings
.ajaxForm
));
482 if (settings
.openInline
) {
483 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
484 $(this).off('.openInline').on('click.openInline', settings
.openInline
, function(e
) {
485 if ($(this).is(exclude
+ ', .crm-popup')) {
488 if ($(this).hasClass('open-inline-noreturn')) {
489 // Force reset of original url
490 $el
.data('civiCrmSnippet')._originalUrl
= $(this).attr('href');
492 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
496 if ($el
.data('uiDialog')) {
497 // Show form buttons as part of the dialog
498 var buttonContainers
= '.crm-submit-buttons, .action-link',
501 $(buttonContainers
, $el
).find('.crm-form-submit, .crm-form-xbutton, a.button, button').each(function() {
503 label
= $el
.is('input') ? $el
.attr('value') : $el
.text(),
504 identifier
= $el
.attr('name') || $el
.attr('href');
505 if (!identifier
|| identifier
=== '#' || $.inArray(identifier
, added
) < 0) {
506 var $icon
= $el
.find('.icon, .crm-i'),
507 button
= {'data-identifier': identifier
, text
: label
, click: function() {
511 button
.icons
= {primary
: $icon
.attr('class')};
513 var action
= $el
.attr('crm-icon') || ($el
.hasClass('cancel') ? 'fa-times' : 'fa-check');
514 button
.icons
= {primary
: action
};
516 buttons
.push(button
);
517 added
.push(identifier
);
519 // display:none causes the form to not submit when pressing "enter"
520 $el
.parents(buttonContainers
).css({height
: 0, padding
: 0, margin
: 0, overflow
: 'hidden'});
522 $el
.dialog('option', 'buttons', buttons
);
524 // Allow a button to prevent ajax submit
525 $('input[data-no-ajax-submit=true], button[data-no-ajax-submit=true]').click(function() {
526 $(this).closest('form').ajaxFormUnbind();
528 // For convenience, focus the first field
529 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
534 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
536 CRM
.popup = function(e
) {
537 var $el
= $(this).first(),
538 url
= $el
.attr('href'),
539 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
540 settings
= $el
.data('popup-settings') || {},
542 settings
.dialog
= settings
.dialog
|| {};
543 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
+ ', .open-inline, .open-inline-noreturn')) {
546 // Sized based on css class
547 if ($el
.hasClass('small-popup')) {
548 settings
.dialog
.width
= 400;
549 settings
.dialog
.height
= 300;
551 else if ($el
.hasClass('medium-popup')) {
552 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
554 var dialog
= popup(url
, settings
);
555 // Trigger events from the dialog on the original link element
556 $el
.trigger('crmPopupOpen', [dialog
]);
557 // Listen for success events and buffer them so we only trigger once
558 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function(e
, data
) {
561 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
563 $el
.trigger('crmPopupFormSuccess', [dialog
, formData
]);
565 $el
.trigger('crmPopupClose', [dialog
, data
]);
570 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
571 * @param e {event|selector}
573 CRM
.refreshParent = function(e
) {
574 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
575 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
576 $table
= $el
.closest('.dataTable');
577 // Call native refresh method on ajax datatables
578 if ($table
.length
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
579 // Refresh ALL datatables - needed for contact relationship tab
580 $.each($.fn
.dataTable
.fnTables(), function() {
581 if ($(this).dataTable().fnSettings().sAjaxSource
) $(this).unblock().dataTable().fnDraw();
584 // Otherwise refresh the nearest crmSnippet
586 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
592 .on('click', 'a.crm-popup', CRM
.popup
)
593 // Close unsaved dialog messages
594 .on('dialogopen', function(e
) {
595 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
597 // Destroy old unsaved dialog
598 .on('dialogcreate', function(e
) {
599 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
601 // Ensure wysiwyg content is updated prior to ajax submit
602 .on('form-pre-serialize', function(e
) {
603 $('.crm-wysiwyg-enabled', e
.target
).each(function() {
604 CRM
.wysiwyg
.updateElement(this);
607 // Auto-resize dialogs when loading content
608 .on('crmLoad dialogopen', 'div.ui-dialog.ui-resizable.crm-container', function(e
) {
611 $dialog
= $wrapper
.children('.ui-dialog-content');
612 // small delay to allow contents to render
613 window
.setTimeout(function() {
614 var currentHeight
= $wrapper
.outerHeight(),
615 padding
= currentHeight
- $dialog
.height(),
616 newHeight
= $dialog
.prop('scrollHeight') + padding
,
617 menuHeight
= $('#civicrm-menu').outerHeight();
618 if ($('body').hasClass('crm-menubar-below-cms-menu')) {
619 menuHeight
+= $('#civicrm-menu').offset().top
;
621 var maxHeight
= $(window
).height() - menuHeight
;
622 newHeight
= newHeight
> maxHeight
? maxHeight
: newHeight
;
623 if (newHeight
> (currentHeight
+ 15)) {
624 $dialog
.dialog('option', {
625 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},