1 // https://civicrm.org/licensing
3 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface
4 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Ajax+Pages+and+Forms
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("*path*", frag
[0]);
29 url
= url
.replace(/[?&]\*query\*/, '');
32 url
= url
.replace("*query*", typeof query
=== 'string' ? query
: $.param(query
));
35 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + frag
[1];
42 function (p
, params
) {
43 CRM
.console('warn', 'Calling crmURL from jQuery is deprecated. Please use CRM.url() instead.');
44 return CRM
.url(p
, params
);
48 $.fn
.crmURL = function () {
49 return this.each(function() {
51 this.href
= CRM
.url(this.href
);
59 CRM
.api3 = function(entity
, action
, params
, status
) {
60 if (typeof(entity
) === 'string') {
63 action
: action
.toLowerCase(),
64 json
: JSON
.stringify(params
|| {})
70 json
: JSON
.stringify(entity
)
75 url
: CRM
.url('civicrm/ajax/rest'),
78 type
: params
.action
.indexOf('get') < 0 ? 'POST' : 'GET'
81 // Default status messages
82 if (status
=== true) {
83 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
84 if (params
.action
.indexOf('get') === 0) {
85 status
.start
= ts('Loading...');
86 status
.success
= null;
89 var messages
= status
=== true ? {} : status
;
90 CRM
.status(status
, ajax
);
99 CRM
.api = function(entity
, action
, params
, options
) {
103 success: function(result
, settings
) {
106 error: function(result
, settings
) {
107 $().crmError(result
.error_message
, ts('Error'));
110 callBack: function(result
, settings
) {
111 if (result
.is_error
== 1) {
112 return settings
.error
.call(this, result
, settings
);
114 return settings
.success
.call(this, result
, settings
);
116 ajaxURL
: 'civicrm/ajax/rest'
118 action
= action
.toLowerCase();
119 // Default success handler
125 settings
.success = function() {
126 CRM
.status(ts('Saved'));
131 settings
.success = function() {
132 CRM
.status(ts('Removed'));
139 json
: JSON
.stringify(params
)
141 // Pass copy of settings into closure to preserve its value during multiple requests
144 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
147 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
148 success: function(result
) {
149 stg
.callBack
.call(stg
.context
, result
, stg
);
152 })($.extend({}, settings
, options
));
156 * Backwards compatible with jQuery fn
159 $.fn
.crmAPI = function(entity
, action
, params
, options
) {
160 CRM
.console('warn', 'Calling crmAPI from jQuery is deprecated. Please use CRM.api3() instead.');
161 return CRM
.api
.call(this, entity
, action
, params
, options
);
164 $.widget('civi.crmSnippet', {
170 _originalContent
: null,
172 isOriginalUrl: function() {
176 newUrl
= this._formatUrl(this.options
.url
),
177 oldUrl
= this._formatUrl(this._originalUrl
);
179 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
183 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
184 var arg
= v
.split('=');
185 args
[arg
[0]] = arg
[1];
187 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
188 var arg
= v
.split('=');
189 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
195 resetUrl: function() {
196 this.options
.url
= this._originalUrl
;
198 _create: function() {
199 this.element
.addClass('crm-ajax-container');
200 if (!this.element
.is('.crm-container *')) {
201 this.element
.addClass('crm-container');
203 this._handleOrderLinks();
204 // Set default if not supplied
205 this.options
.url
= this.options
.url
|| document
.location
.href
;
206 this._originalUrl
= this.options
.url
;
208 _onFailure: function(data
, status
) {
209 var msg
, title
= ts('Network Error');
210 if (this.options
.block
) this.element
.unblock();
211 this.element
.trigger('crmAjaxFail', data
);
214 title
= ts('Access Denied');
215 msg
= ts('Ensure you are still logged in and have permission to access this feature.');
218 msg
= ts('Unable to reach the server. Please refresh this page in your browser and try again.');
220 CRM
.alert(msg
, title
, 'error');
222 _onError: function(data
) {
223 this.element
.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data
);
224 if (this.options
.crmForm
&& this.options
.crmForm
.autoClose
&& this.element
.data('uiDialog')) {
225 this.element
.dialog('close');
228 _formatUrl: function(url
) {
230 url
= url
.split('#')[0];
231 // Add snippet argument to url
232 if (url
.search(/[&?]snippet=/) < 0) {
233 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
235 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
239 // Hack to deal with civicrm legacy sort functionality
240 _handleOrderLinks: function() {
242 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
243 if (that
.options
.block
) that
.element
.block();
244 $.getJSON(that
._formatUrl(this.href
)).done(function() {
247 e
.stopImmediatePropagation();
251 refresh: function() {
253 var url
= this._formatUrl(this.options
.url
);
254 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
255 if (this._originalContent
=== null) {
256 this._originalContent
= this.element
.contents().detach();
258 if (this.options
.block
) this.element
.block();
259 $.getJSON(url
, function(data
) {
260 if (that
.options
.block
) that
.element
.unblock();
261 if (!$.isPlainObject(data
)) {
262 that
._onFailure(data
);
265 if (data
.status
=== 'error') {
270 that
.element
.trigger('crmUnload').trigger('crmBeforeLoad', data
);
271 that
._beforeRemovingContent();
272 that
.element
.html(data
.content
);
273 that
._handleOrderLinks();
274 that
.element
.trigger('crmLoad', data
);
275 if (that
.options
.crmForm
) that
.element
.trigger('crmFormLoad', data
);
276 }).fail(function(data
, msg
, status
) {
277 that
._onFailure(data
, status
);
280 // Perform any cleanup needed before removing/replacing content
281 _beforeRemovingContent: function() {
283 if (window
.tinyMCE
&& tinyMCE
.editors
) {
284 $.each(tinyMCE
.editors
, function(k
) {
285 if ($.contains(that
.element
[0], this.getElement())) {
290 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
292 _destroy: function() {
293 this.element
.removeClass('crm-ajax-container').trigger('crmUnload');
294 this._beforeRemovingContent();
295 if (this._originalContent
!== null) {
296 this.element
.empty().append(this._originalContent
);
302 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
304 CRM
.loadPage = function(url
, options
) {
306 target
: '#crm-ajax-dialog-' + (dialogCount
++),
309 if (!options
|| !options
.target
) {
316 if (options
) $.extend(true, settings
, options
);
319 if (settings
.dialog
) {
320 // HACK: jQuery UI doesn't support relative height
321 if (typeof settings
.dialog
.height
=== 'string' && settings
.dialog
.height
.indexOf('%') > 0) {
322 settings
.dialog
.height
= parseInt($(window
).height() * (parseFloat(settings
.dialog
.height
)/100), 10);
324 // Increase percent width on small screens
325 if (typeof settings
.dialog
.width
=== 'string' && settings
.dialog
.width
.indexOf('%') > 0) {
326 var screenWidth
= $(window
).width(),
327 percentage
= parseInt(settings
.dialog
.width
.replace('%', ''), 10),
328 gap
= 100-percentage
;
329 if (screenWidth
< 701) {
330 settings
.dialog
.width
= '100%';
332 else if (screenWidth
< 1400) {
333 settings
.dialog
.width
= '' + parseInt(percentage
+gap
-((screenWidth
- 700)/7*(gap)/100), 10) + '%';
336 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
338 .on('dialogclose', function() {
339 if ($(this).attr('data-unsaved-changes') !== 'true') {
340 $(this).crmSnippet('destroy').dialog('destroy').remove();
343 .on('crmLoad', function(e
, data
) {
345 if (e
.target
=== $(settings
.target
)[0] && data
&& !settings
.dialog
.title
&& data
.title
) {
346 $(this).dialog('option', 'title', data
.title
);
348 // Adjust height to fit content (small delay to allow elements to render)
349 window
.setTimeout(function() {
350 var currentHeight
= $(settings
.target
).parent().outerHeight(),
351 padding
= currentHeight
- $(settings
.target
).height(),
352 newHeight
= $(settings
.target
).prop('scrollHeight') + padding
,
353 menuHeight
= $('#civicrm-menu').outerHeight(),
354 maxHeight
= $(window
).height() - menuHeight
;
355 newHeight
= newHeight
> maxHeight
? maxHeight
: newHeight
;
356 if (newHeight
> (currentHeight
+ 15)) {
357 $(settings
.target
).dialog('option', {
358 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},
365 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
366 return $(settings
.target
);
368 CRM
.loadForm = function(url
, options
) {
369 var formErrors
= [], settings
= {
374 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
375 cancelButton
: '.cancel',
376 openInline
: 'a.open-inline, a.button, a.action-item',
377 onCancel: function(event
) {}
380 // Move options that belong to crmForm. Others will be passed through to crmSnippet
381 if (options
) $.each(options
, function(key
, value
) {
382 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
383 settings
.crmForm
[key
] = value
;
386 settings
[key
] = value
;
390 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
392 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
393 function cancelAction() {
394 var dirty
= CRM
.utils
.initialValueChanged($('form:not([data-warn-changes=false])', widget
));
395 widget
.attr('data-unsaved-changes', dirty
? 'true' : 'false');
397 var id
= widget
.attr('id') + '-unsaved-alert',
398 title
= widget
.dialog('option', 'title'),
399 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});
400 $('#' + id
).button({icons
: {primary
: 'ui-icon-arrowreturnthick-1-w'}}).click(function(e
) {
401 widget
.attr('data-unsaved-changes', 'false').dialog('open');
407 if (widget
.data('uiDialog')) widget
.on('dialogbeforeclose', function(e
) {
408 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
409 if (e
.originalEvent
) {
414 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
415 var $el
= $(this).attr('data-unsaved-changes', 'false'),
416 settings
= $el
.crmSnippet('option', 'crmForm');
417 if (settings
.cancelButton
) $(settings
.cancelButton
, this).click(function(e
) {
419 var returnVal
= settings
.onCancel
.call($el
, e
);
420 if (returnVal
!== false) {
421 $el
.trigger('crmFormCancel', e
);
422 if ($el
.data('uiDialog') && settings
.autoClose
) {
426 else if (!settings
.autoClose
) {
427 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
431 if (settings
.validate
) {
432 $("form", this).crmValidate();
434 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
435 url
: data
.url
.replace(/reset=1[&]?/, ''),
437 success: function(response
) {
438 if (response
.content
=== undefined) {
439 $el
.trigger('crmFormSuccess', response
);
440 // Reset form for e.g. "save and new"
441 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
442 // Force reset of original url
443 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
444 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
446 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
447 else if ($el
.data('uiDialog') && (settings
.autoClose
|| response
.action
=== 8)) {
450 else if (settings
.autoClose
=== false) {
451 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
455 if ($el
.crmSnippet('option', 'block')) $el
.unblock();
456 response
.url
= data
.url
;
457 $el
.html(response
.content
).trigger('crmLoad', response
).trigger('crmFormLoad', response
);
458 if (response
.status
=== 'form_error') {
460 $el
.trigger('crmFormError', response
);
461 $.each(response
.errors
|| [], function(formElement
, msg
) {
462 formErrors
.push($('[name="'+formElement
+'"]', $el
).crmError(msg
));
467 beforeSerialize: function(form
, options
) {
468 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
469 $.each(CKEDITOR
.instances
, function() {
470 if (this.updateElement
) this.updateElement();
473 if (window
.tinyMCE
&& tinyMCE
.editors
) {
474 $.each(tinyMCE
.editors
, function() {
479 beforeSubmit: function(submission
) {
480 $.each(formErrors
, function() {
481 if (this && this.close
) this.close();
483 if ($el
.crmSnippet('option', 'block')) $el
.block();
484 $el
.trigger('crmFormSubmit', submission
);
486 }, settings
.ajaxForm
));
487 if (settings
.openInline
) {
488 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
489 $(settings
.openInline
, this).not(exclude
+ ', .crm-popup').click(function(event
) {
490 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
494 // Show form buttons as part of the dialog
495 if ($el
.data('uiDialog')) {
496 var buttonContainers
= '.crm-submit-buttons, .action-link',
499 $(buttonContainers
, $el
).find('input.crm-form-submit, a.button').each(function() {
501 label
= $el
.is('input') ? $el
.attr('value') : $el
.text(),
502 identifier
= $el
.attr('name') || $el
.attr('href');
503 if (!identifier
|| identifier
=== '#' || $.inArray(identifier
, added
) < 0) {
504 var $icon
= $el
.find('.icon'),
505 button
= {'data-identifier': identifier
, text
: label
, click: function() {
509 button
.icons
= {primary
: $icon
.attr('class')};
511 var action
= $el
.hasClass('cancel') ? 'close' : (identifier
.substr(identifier
.length
-4) === '_new' ? 'plus' : 'check');
512 button
.icons
= {primary
: 'ui-icon-' + action
};
514 buttons
.push(button
);
515 added
.push(identifier
);
517 // display:none causes the form to not submit when pressing "enter"
518 $el
.parents(buttonContainers
).css({height
: 0, padding
: 0, margin
: 0, overflow
: 'hidden'});
520 $el
.dialog('option', 'buttons', buttons
);
522 // Allow a button to prevent ajax submit
523 $('input[data-no-ajax-submit=true]').click(function() {
524 $(this).closest('form').ajaxFormUnbind();
526 // For convenience, focus the first field
527 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
532 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
534 CRM
.popup = function(e
) {
535 var $el
= $(this).first(),
536 url
= $el
.attr('href'),
537 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
538 settings
= $el
.data('popup-settings') || {},
540 settings
.dialog
= settings
.dialog
|| {};
541 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
)) {
544 // Sized based on css class
545 if ($el
.hasClass('small-popup')) {
546 settings
.dialog
.width
= 400;
547 settings
.dialog
.height
= 300;
549 else if ($el
.hasClass('medium-popup')) {
550 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
552 var dialog
= popup(url
, settings
);
553 // Trigger events from the dialog on the original link element
554 $el
.trigger('crmPopupOpen', [dialog
]);
555 // Listen for success events and buffer them so we only trigger once
556 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
559 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
561 $el
.trigger('crmPopupFormSuccess', [dialog
, data
]);
563 $el
.trigger('crmPopupClose', [dialog
, data
]);
568 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
569 * @param e {event|selector}
571 CRM
.refreshParent = function(e
) {
572 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
573 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
574 $table
= $el
.closest('.dataTable');
575 // Call native refresh method on ajax datatables
576 if ($table
.length
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
577 // Refresh ALL datatables - needed for contact relationship tab
578 $.each($.fn
.dataTable
.fnTables(), function() {
579 if ($(this).dataTable().fnSettings().sAjaxSource
) $(this).unblock().dataTable().fnDraw();
582 // Otherwise refresh the nearest crmSnippet
584 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
590 .on('click', 'a.crm-popup', CRM
.popup
)
591 // Close unsaved dialog messages
592 .on('dialogopen', function(e
) {
593 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
595 // Destroy old unsaved dialog
596 .on('dialogcreate', function(e
) {
597 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();