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
8 * Almost like {crmURL} but on the client side
9 * eg: var url = CRM.url('civicrm/contact/view', {reset:1,cid:42});
10 * or: $('a.my-link').crmURL();
12 var tplURL
= '/civicrm/example?placeholder';
13 var urlInitted
= false;
14 CRM
.url = function (p
, params
) {
21 console
&& console
.log
&& console
.log('Warning: CRM.url called before initialization');
23 params
= params
|| '';
24 var frag
= p
.split ('?');
25 var url
= tplURL
.replace("civicrm/example", frag
[0]);
27 if (typeof(params
) == 'string') {
28 url
= url
.replace("placeholder", params
);
31 url
= url
.replace("placeholder", $.param(params
));
34 url
+= (url
.indexOf('?') === (url
.length
- 1) ? '' : '&') + frag
[1];
36 // remove trailing "?"
37 if (url
.indexOf('?') === (url
.length
- 1)) {
38 url
= url
.slice(0, (url
.length
- 1));
43 // Backwards compatible with jQuery fn
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
);
51 $.fn
.crmURL = function () {
52 return this.each(function() {
54 this.href
= CRM
.url(this.href
);
62 CRM
.api3 = function(entity
, action
, params
, status
) {
63 if (typeof(entity
) === 'string') {
66 action
: action
.toLowerCase(),
67 json
: JSON
.stringify(params
|| {})
73 json
: JSON
.stringify(entity
)
77 url
: CRM
.url('civicrm/ajax/rest'),
80 type
: params
.action
.indexOf('get') < 0 ? 'POST' : 'GET'
83 // Default status messages
84 if (status
=== true) {
85 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
86 if (params
.action
.indexOf('get') === 0) {
87 status
.start
= ts('Loading...');
88 status
.success
= null;
91 var messages
= status
=== true ? {} : status
;
92 CRM
.status(status
, ajax
);
101 CRM
.api = function(entity
, action
, params
, options
) {
105 success: function(result
, settings
) {
108 error: function(result
, settings
) {
109 $().crmError(result
.error_message
, ts('Error'));
112 callBack: function(result
, settings
) {
113 if (result
.is_error
== 1) {
114 return settings
.error
.call(this, result
, settings
);
116 return settings
.success
.call(this, result
, settings
);
118 ajaxURL
: 'civicrm/ajax/rest'
120 action
= action
.toLowerCase();
121 // Default success handler
127 settings
.success = function() {
128 CRM
.status(ts('Saved'));
133 settings
.success = function() {
134 CRM
.status(ts('Removed'));
141 json
: JSON
.stringify(params
)
143 // Pass copy of settings into closure to preserve its value during multiple requests
146 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
149 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
150 success: function(result
) {
151 stg
.callBack
.call(stg
.context
, result
, stg
);
154 })($.extend({}, settings
, options
));
158 * Backwards compatible with jQuery fn
161 $.fn
.crmAPI = function(entity
, action
, params
, options
) {
162 console
&& console
.log
&& console
.log('Calling crmAPI from jQuery is deprecated. Please use CRM.api() instead.');
163 return CRM
.api
.call(this, entity
, action
, params
, options
);
166 $.widget('civi.crmSnippet', {
172 _originalContent
: null,
174 isOriginalUrl: function() {
178 newUrl
= this._formatUrl(this.options
.url
),
179 oldUrl
= this._formatUrl(this._originalUrl
);
181 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
185 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
186 var arg
= v
.split('=');
187 args
[arg
[0]] = arg
[1];
189 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
190 var arg
= v
.split('=');
191 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
197 resetUrl: function() {
198 this.options
.url
= this._originalUrl
;
200 _create: function() {
201 this.element
.addClass('crm-ajax-container');
202 if (!this.element
.is('.crm-container *')) {
203 this.element
.addClass('crm-container');
205 this._handleOrderLinks();
206 // Set default if not supplied
207 this.options
.url
= this.options
.url
|| document
.location
.href
;
208 this._originalUrl
= this.options
.url
;
210 _onFailure: function(data
) {
211 this.options
.block
&& this.element
.unblock();
212 this.element
.trigger('crmAjaxFail', data
);
213 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
215 _formatUrl: function(url
) {
217 url
= url
.split('#')[0];
218 // Add snippet argument to url
219 if (url
.search(/[&?]snippet=/) < 0) {
220 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
222 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
226 // Hack to deal with civicrm legacy sort functionality
227 _handleOrderLinks: function() {
229 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
230 that
.options
.block
&& that
.element
.block();
231 $.getJSON(that
._formatUrl(this.href
)).done(function() {
234 e
.stopImmediatePropagation();
238 refresh: function() {
240 var url
= this._formatUrl(this.options
.url
);
241 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
242 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
243 $.getJSON(url
, function(data
) {
244 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
245 that
._onFailure(data
);
249 that
.element
.trigger('crmBeforeLoad', data
);
250 if (that
._originalContent
=== null) {
251 that
._originalContent
= that
.element
.contents().detach();
253 that
.element
.html(data
.content
);
254 that
._handleOrderLinks();
255 that
.element
.trigger('crmLoad', data
);
256 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
261 _destroy: function() {
262 this.element
.removeClass('crm-ajax-container');
263 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
264 if (this._originalContent
!== null) {
265 this.element
.empty().append(this._originalContent
);
271 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
273 CRM
.loadPage = function(url
, options
) {
275 target
: '#crm-ajax-dialog-' + (dialogCount
++),
278 if (!options
|| !options
.target
) {
285 options
&& $.extend(true, settings
, options
);
288 if (settings
.dialog
) {
289 // HACK: jQuery UI doesn't support relative height
290 if (typeof settings
.dialog
.height
=== 'string' && settings
.dialog
.height
.indexOf('%') > 0) {
291 settings
.dialog
.height
= parseInt($(window
).height() * (parseFloat(settings
.dialog
.height
)/100), 10);
293 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
294 $(settings
.target
).on('dialogclose', function() {
295 $(this).crmSnippet('destroy').dialog('destroy').remove();
298 if (settings
.dialog
&& !settings
.dialog
.title
) {
299 $(settings
.target
).on('crmLoad', function(e
, data
) {
300 if (e
.target
=== $(settings
.target
)[0] && data
&& data
.title
) {
301 $(this).dialog('option', 'title', data
.title
);
305 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
306 return $(settings
.target
);
308 CRM
.loadForm = function(url
, options
) {
314 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
315 cancelButton
: '.cancel',
316 openInline
: 'a.open-inline, a.button, a.action-item',
317 onCancel: function(event
) {},
318 onError: function(data
) {
320 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
).trigger('crmFormError', data
);
321 if (typeof(data
.errors
) == 'object') {
322 $.each(data
.errors
, function(formElement
, msg
) {
323 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
329 // Move options that belong to crmForm. Others will be passed through to crmSnippet
330 options
&& $.each(options
, function(key
, value
) {
331 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
332 settings
.crmForm
[key
] = value
;
335 settings
[key
] = value
;
339 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
341 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
343 var settings
= $el
.crmSnippet('option', 'crmForm');
344 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(event
) {
345 var returnVal
= settings
.onCancel
.call($el
, event
);
346 if (returnVal
!== false) {
347 $el
.trigger('crmFormCancel', event
);
348 if ($el
.data('uiDialog') && settings
.autoClose
) {
351 else if (!settings
.autoClose
) {
352 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
355 return returnVal
=== false;
357 if (settings
.validate
) {
358 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
360 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
361 url
: data
.url
.replace(/reset=1[&]?/, ''),
363 success: function(response
) {
364 if (response
.status
!== 'form_error') {
365 $el
.crmSnippet('option', 'block') && $el
.unblock();
366 $el
.trigger('crmFormSuccess', response
);
367 // Reset form for e.g. "save and new"
368 if (response
.userContext
&& settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0) {
369 $el
.crmSnippet('option', 'url', response
.userContext
).crmSnippet('refresh');
371 else if ($el
.data('uiDialog') && settings
.autoClose
) {
374 else if (settings
.autoClose
=== false) {
375 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
379 response
.url
= data
.url
;
380 settings
.onError
.call($el
, response
);
383 beforeSerialize: function(form
, options
) {
384 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
385 $.each(CKEDITOR
.instances
, function() {
386 this.updateElement
&& this.updateElement();
390 beforeSubmit: function(submission
) {
391 $el
.crmSnippet('option', 'block') && $el
.block();
392 $el
.trigger('crmFormSubmit', submission
);
394 }, settings
.ajaxForm
));
395 if (settings
.openInline
) {
396 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
397 $(settings
.openInline
, this).not(exclude
+ ', .crm-popup').click(function(event
) {
398 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
402 // For convenience, focus the first field
403 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
408 * Handler for jQuery click event e.g. $('a').click(CRM.popup)
411 CRM
.popup = function() {
412 var $el
= $(this).first(),
413 url
= $el
.attr('href'),
414 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
415 settings
= $el
.data('popup-settings') || {},
416 triggers
= {dialogclose
: 'crmPopupClose', crmLoad
: 'crmPopupLoad', crmFormSuccess
: 'crmPopupFormSuccess'};
417 settings
.dialog
= settings
.dialog
|| {};
418 if (!CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
)) {
421 // Sized based on css class
422 if ($el
.hasClass('small-popup')) {
423 settings
.dialog
.width
= 400;
424 settings
.dialog
.height
= 300;
426 else if ($el
.hasClass('medium-popup')) {
427 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
429 else if ($el
.hasClass('huge-popup')) {
430 settings
.dialog
.height
= '90%';
432 var dialog
= popup(url
, settings
);
433 // Trigger events from the dialog on the original link element
434 $el
.trigger('crmPopupOpen', [dialog
]);
435 $.each(triggers
, function(event
, target
) {
436 dialog
.on(event
, function(e
, data
) {
437 $el
.trigger(target
, [dialog
, data
]);
444 $('body').on('click', 'a.crm-popup', CRM
.popup
);