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