Merge pull request #3066 from relldoesphp/CRM-14466
[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) {
7 /**
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();
11 */
12 var tplURL = '/civicrm/example?placeholder';
13 var urlInitted = false;
14 CRM.url = function (p, params) {
15 if (p == "init") {
16 tplURL = params;
17 urlInitted = true;
18 return;
19 }
20 if (!urlInitted) {
21 console && console.log && console.log('Warning: CRM.url called before initialization');
22 }
23 params = params || '';
24 var frag = p.split ('?');
25 var url = tplURL.replace("civicrm/example", frag[0]);
26
27 if (typeof(params) == 'string') {
28 url = url.replace("placeholder", params);
29 }
30 else {
31 url = url.replace("placeholder", $.param(params));
32 }
33 if (frag[1]) {
34 url += (url.indexOf('?') === (url.length - 1) ? '' : '&') + frag[1];
35 }
36 // remove trailing "?"
37 if (url.indexOf('?') === (url.length - 1)) {
38 url = url.slice(0, (url.length - 1));
39 }
40 return url;
41 };
42
43 // Backwards compatible with jQuery fn
44 $.extend ({'crmURL':
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);
48 }
49 });
50
51 $.fn.crmURL = function () {
52 return this.each(function() {
53 if (this.href) {
54 this.href = CRM.url(this.href);
55 }
56 });
57 };
58
59 /**
60 * AJAX api
61 */
62 CRM.api3 = function(entity, action, params, status) {
63 if (typeof(entity) === 'string') {
64 params = {
65 entity: entity,
66 action: action.toLowerCase(),
67 json: JSON.stringify(params || {})
68 };
69 } else {
70 params = {
71 entity: 'api3',
72 action: 'call',
73 json: JSON.stringify(entity)
74 }
75 }
76 var ajax = $.ajax({
77 url: CRM.url('civicrm/ajax/rest'),
78 dataType: 'json',
79 data: params,
80 type: params.action.indexOf('get') < 0 ? 'POST' : 'GET'
81 });
82 if (status) {
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;
89 }
90 }
91 var messages = status === true ? {} : status;
92 CRM.status(status, ajax);
93 }
94 return ajax;
95 };
96
97 /**
98 * @deprecated
99 * AJAX api
100 */
101 CRM.api = function(entity, action, params, options) {
102 // Default settings
103 var settings = {
104 context: null,
105 success: function(result, settings) {
106 return true;
107 },
108 error: function(result, settings) {
109 $().crmError(result.error_message, ts('Error'));
110 return false;
111 },
112 callBack: function(result, settings) {
113 if (result.is_error == 1) {
114 return settings.error.call(this, result, settings);
115 }
116 return settings.success.call(this, result, settings);
117 },
118 ajaxURL: 'civicrm/ajax/rest'
119 };
120 action = action.toLowerCase();
121 // Default success handler
122 switch (action) {
123 case "update":
124 case "create":
125 case "setvalue":
126 case "replace":
127 settings.success = function() {
128 CRM.status(ts('Saved'));
129 return true;
130 };
131 break;
132 case "delete":
133 settings.success = function() {
134 CRM.status(ts('Removed'));
135 return true;
136 };
137 }
138 params = {
139 entity: entity,
140 action: action,
141 json: JSON.stringify(params)
142 };
143 // Pass copy of settings into closure to preserve its value during multiple requests
144 (function(stg) {
145 $.ajax({
146 url: stg.ajaxURL.indexOf('http') === 0 ? stg.ajaxURL : CRM.url(stg.ajaxURL),
147 dataType: 'json',
148 data: params,
149 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
150 success: function(result) {
151 stg.callBack.call(stg.context, result, stg);
152 }
153 });
154 })($.extend({}, settings, options));
155 };
156
157 /**
158 * Backwards compatible with jQuery fn
159 * @deprecated
160 */
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);
164 };
165
166 $.widget('civi.crmSnippet', {
167 options: {
168 url: null,
169 block: true,
170 crmForm: null
171 },
172 _originalContent: null,
173 _originalUrl: null,
174 isOriginalUrl: function() {
175 var
176 args = {},
177 same = true,
178 newUrl = this._formatUrl(this.options.url),
179 oldUrl = this._formatUrl(this._originalUrl);
180 // Compare path
181 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
182 return false;
183 }
184 // Compare arguments
185 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
186 var arg = v.split('=');
187 args[arg[0]] = arg[1];
188 });
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]]) {
192 same = false;
193 }
194 });
195 return same;
196 },
197 resetUrl: function() {
198 this.options.url = this._originalUrl;
199 },
200 _create: function() {
201 this.element.addClass('crm-ajax-container');
202 if (!this.element.is('.crm-container *')) {
203 this.element.addClass('crm-container');
204 }
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;
209 },
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');
214 },
215 _formatUrl: function(url) {
216 // Strip hash
217 url = url.split('#')[0];
218 // Add snippet argument to url
219 if (url.search(/[&?]snippet=/) < 0) {
220 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
221 } else {
222 url = url.replace(/snippet=[^&]*/, 'snippet=json');
223 }
224 return url;
225 },
226 // Hack to deal with civicrm legacy sort functionality
227 _handleOrderLinks: function() {
228 var that = this;
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() {
232 that.refresh();
233 });
234 e.stopImmediatePropagation();
235 return false;
236 });
237 },
238 refresh: function() {
239 var that = this;
240 var url = this._formatUrl(this.options.url);
241 this.options.crmForm && $('form', this.element).ajaxFormUnbind();
242 if (this._originalContent === null) {
243 this._originalContent = this.element.contents().detach();
244 }
245 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
246 $.getJSON(url, function(data) {
247 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
248 that._onFailure(data);
249 return;
250 }
251 data.url = url;
252 that.element.trigger('crmBeforeLoad', data).html(data.content);
253 that._handleOrderLinks();
254 that.element.trigger('crmLoad', data);
255 that.options.crmForm && that.element.trigger('crmFormLoad', data);
256 }).fail(function() {
257 that._onFailure();
258 });
259 },
260 _destroy: function() {
261 this.element.removeClass('crm-ajax-container');
262 this.options.crmForm && $('form', this.element).ajaxFormUnbind();
263 if (this._originalContent !== null) {
264 this.element.empty().append(this._originalContent);
265 }
266 }
267 });
268
269 var dialogCount = 0,
270 exclude = '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
271
272 CRM.loadPage = function(url, options) {
273 var settings = {
274 target: '#crm-ajax-dialog-' + (dialogCount++),
275 dialog: false
276 };
277 if (!options || !options.target) {
278 settings.dialog = {
279 modal: true,
280 width: '65%',
281 height: '75%'
282 };
283 }
284 options && $.extend(true, settings, options);
285 settings.url = url;
286 // Create new dialog
287 if (settings.dialog) {
288 // HACK: jQuery UI doesn't support relative height
289 if (typeof settings.dialog.height === 'string' && settings.dialog.height.indexOf('%') > 0) {
290 settings.dialog.height = parseInt($(window).height() * (parseFloat(settings.dialog.height)/100), 10);
291 }
292 $('<div id="'+ settings.target.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings.dialog);
293 $(settings.target).on('dialogclose', function() {
294 $(this).crmSnippet('destroy').dialog('destroy').remove();
295 });
296 }
297 if (settings.dialog && !settings.dialog.title) {
298 $(settings.target).on('crmLoad', function(e, data) {
299 if (e.target === $(settings.target)[0] && data && data.title) {
300 $(this).dialog('option', 'title', data.title);
301 }
302 });
303 }
304 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
305 return $(settings.target);
306 };
307 CRM.loadForm = function(url, options) {
308 var settings = {
309 crmForm: {
310 ajaxForm: {},
311 autoClose: true,
312 validate: true,
313 refreshAction: ['next_new', 'submit_savenext', 'upload_new'],
314 cancelButton: '.cancel',
315 openInline: 'a.open-inline, a.button, a.action-item',
316 onCancel: function(event) {},
317 onError: function(data) {
318 var $el = $(this);
319 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
320 if (typeof(data.errors) == 'object') {
321 $.each(data.errors, function(formElement, msg) {
322 $('[name="'+formElement+'"]', $el).crmError(msg);
323 });
324 }
325 }
326 }
327 };
328 // Move options that belong to crmForm. Others will be passed through to crmSnippet
329 options && $.each(options, function(key, value) {
330 if (typeof(settings.crmForm[key]) !== 'undefined') {
331 settings.crmForm[key] = value;
332 }
333 else {
334 settings[key] = value;
335 }
336 });
337
338 var widget = CRM.loadPage(url, settings).off('.crmForm');
339
340 widget.on('crmFormLoad.crmForm', function(event, data) {
341 var $el = $(this);
342 var settings = $el.crmSnippet('option', 'crmForm');
343 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
344 var returnVal = settings.onCancel.call($el, event);
345 if (returnVal !== false) {
346 $el.trigger('crmFormCancel', event);
347 if ($el.data('uiDialog') && settings.autoClose) {
348 $el.dialog('close');
349 }
350 else if (!settings.autoClose) {
351 $el.crmSnippet('resetUrl').crmSnippet('refresh');
352 }
353 }
354 return returnVal === false;
355 });
356 if (settings.validate) {
357 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
358 }
359 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
360 url: data.url.replace(/reset=1[&]?/, ''),
361 dataType: 'json',
362 success: function(response) {
363 if (response.status !== 'form_error') {
364 $el.crmSnippet('option', 'block') && $el.unblock();
365 $el.trigger('crmFormSuccess', response);
366 // Reset form for e.g. "save and new"
367 if (response.userContext && (response.status === 'redirect' || (settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0))) {
368 // Force reset of original url
369 $el.data('civiCrmSnippet')._originalUrl = response.userContext;
370 $el.crmSnippet('resetUrl').crmSnippet('refresh');
371 }
372 else if ($el.data('uiDialog') && settings.autoClose) {
373 $el.dialog('close');
374 }
375 else if (settings.autoClose === false) {
376 $el.crmSnippet('resetUrl').crmSnippet('refresh');
377 }
378 }
379 else {
380 response.url = data.url;
381 settings.onError.call($el, response);
382 }
383 },
384 beforeSerialize: function(form, options) {
385 if (window.CKEDITOR && window.CKEDITOR.instances) {
386 $.each(CKEDITOR.instances, function() {
387 this.updateElement && this.updateElement();
388 });
389 }
390 },
391 beforeSubmit: function(submission) {
392 $el.crmSnippet('option', 'block') && $el.block();
393 $el.trigger('crmFormSubmit', submission);
394 }
395 }, settings.ajaxForm));
396 if (settings.openInline) {
397 settings.autoClose = $el.crmSnippet('isOriginalUrl');
398 $(settings.openInline, this).not(exclude + ', .crm-popup').click(function(event) {
399 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
400 return false;
401 });
402 }
403 // For convenience, focus the first field
404 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
405 });
406 return widget;
407 };
408 /**
409 * Handler for jQuery click event e.g. $('a').click(CRM.popup)
410 * @returns {boolean}
411 */
412 CRM.popup = function(e) {
413 var $el = $(this).first(),
414 url = $el.attr('href'),
415 popup = $el.data('popup-type') === 'page' ? CRM.loadPage : CRM.loadForm,
416 settings = $el.data('popup-settings') || {},
417 formSuccess = false;
418 settings.dialog = settings.dialog || {};
419 if (e.isDefaultPrevented() || !CRM.config.ajaxPopupsEnabled || !url || $el.is(exclude)) {
420 return;
421 }
422 // Sized based on css class
423 if ($el.hasClass('small-popup')) {
424 settings.dialog.width = 400;
425 settings.dialog.height = 300;
426 }
427 else if ($el.hasClass('medium-popup')) {
428 settings.dialog.width = settings.dialog.height = '50%';
429 }
430 else if ($el.hasClass('huge-popup')) {
431 settings.dialog.height = '90%';
432 }
433 var dialog = popup(url, settings);
434 // Trigger events from the dialog on the original link element
435 $el.trigger('crmPopupOpen', [dialog]);
436 // Listen for success events and buffer them so we only trigger once
437 dialog.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
438 formSuccess = true;
439 });
440 dialog.on('dialogclose.crmPopup', function(e, data) {
441 if (formSuccess) {
442 $el.trigger('crmPopupFormSuccess', [dialog, data]);
443 }
444 $el.trigger('crmPopupClose', [dialog, data]);
445 });
446 e.preventDefault();
447 };
448 /**
449 * An event callback for CRM.popup or a standalone function to refresh the content around a popup link
450 * @param e event|selector
451 */
452 CRM.refreshParent = function(e) {
453 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
454 var $el = (e.stopPropagation && e.target) ? $(e.target) : $(e),
455 $table = $el.closest('.dataTable');
456 // Call native refresh method on ajax datatables
457 if ($table && $.fn.DataTable.fnIsDataTable($table[0]) && $table.dataTable().fnSettings().sAjaxSource) {
458 // Refresh ALL datatables - needed for contact relationship tab
459 $.each($.fn.dataTable.fnTables(), function() {
460 $(this).dataTable().fnSettings().sAjaxSource && $(this).unblock().dataTable().fnDraw();
461 });
462 }
463 // Otherwise refresh the nearest crmSnippet
464 else {
465 $el.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
466 }
467 };
468
469 $(function($) {
470 $('body').on('click', 'a.crm-popup', CRM.popup);
471 });
472
473 }(jQuery, CRM));