-
Notifications
You must be signed in to change notification settings - Fork 0
/
AJAXRequest.js
1718 lines (1660 loc) · 74.2 KB
/
AJAXRequest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
Object.defineProperties(AJAXRequest, {
META: {
writable: false,
value: {}
},
CALLBACK_POOLS: {
/**
* Names of pools of events.
* @type Array
*/
value: ['servererror', 'clienterror', 'success', 'connectionlost', 'afterajax', 'beforeajax', 'error'],
writable: false
},
XMLHttpFactories: {
/**
* Array of functions used to create XMLHttpRequest object.
* @type Array
*/
value: [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject("Microsoft.XMLHTTP"); },
function () { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); }
],
writable: false
},
createXhr: {
/**
* A factory function used to create XHR object for diffrent browsers.
* @returns {Mixed} False in case of failure. Other than that, it will
* return XHR object that can be used to send AJAX.
*/
value: function createXhr() {
for (var i = 0; i < AJAXRequest.XMLHttpFactories.length; i++) {
try {
var instance = AJAXRequest.XMLHttpFactories[i]();
instance.active = false;
return instance;
}
catch (e) {
}
}
return false;
},
wriable: false
},
extractBase: {
/**
* Extract the value of the attribute 'href' of the 'base' tag.
*
* @returns {String|null} If the tag 'base' and the attribute 'base' is set,
* the method will return its value. Other than that, the method will return
* null.
*/
value: function () {
var base = null;
var baseTagsArr = document.getElementsByTagName('base');
if (baseTagsArr.length === 1) {
var baseTag = baseTagsArr[0];
base = baseTag.getAttribute('href');
if (base !== null && base.length === 0) {
base = null;
}
}
return base;
}
},
isValidURL: {
/**
* Checks if given string represents a valid URL or not.
*
* @param {String} url The string that will be validated.
*
* @returns {Boolean} If the given string is a valid URL, the method will return true.
* Other than that, the method will return false.
*/
value: function (url) {
var pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
'(\\:\\d+)?(\\/[-a-z\\d%_.=~+!]*)*' + // port and path
'(\\?[;&a-z\\d%_.~+=/-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', 'i'); // fragment locator
return !!pattern.test(url);
}
}
});
Object.defineProperties(AJAXRequest.META, {
VERSION: {
value: '2.1.9',
writable: false
},
REALSE_DATE: {
value: '2023-07-19',
writable: false
},
CONTRIBUTORS: {
value: [
{
name: 'Ibrahim Ali BinAlshikh',
email: '[email protected]'
},
{
name: 'Ibrahim Beladi',
email: ''
}
],
writable: false
}
});
/**
* A class that can be used to simplfy AJAX requests.
* @author Ibrahim BinAlshikh <[email protected]>
* @constructor
* @param {Object} config AJAX configuration. The object can have the
* following properties:
* <ul>
* <li><b>method</b>: Request method such as GET or POST.</li>
* <li><b>url</b>: The URL at which AJAX request will be sent
* to.</li>
* <li><b>params</b>: A parameters which will be sent with the request.
* It can be an object, a FormData or a query string.</li>
* <li><b>verbose</b>:A boolean Used for development. If set to true, more
* informative messages will appear in the console.</li>
* <li><b>headers</b>: An object that can hold custom headers that will be
* sent with the request.</li>
* <li><b>enabled</b>: A boolean to enable or disable AJAX.</li>
* <li><b>beforeAjax</b>: An array that contains one or more callbacks which
* will be executed before AJAX request is sent. The callbacks can
* be used to collect user inputs and do final configuration before sending
* the request to the server.</li>
* <li><b>onSuccess</b>: An array that contains one or more callbacks which
* will be executed when server sends the response code 2xx.</li>
* <li><b>onClientErr</b>: An array that contains one or more callbacks which
* will be executed when server sends the response code 4xx.</li>
* <li><b>onServerErr</b>: An array that contains one or more callbacks which
* will be executed when server sends the response code 5xx.</li>
* <li><b>onDisconnected</b>: An array that contains one or more callbacks which
* will be executed when there is no internet connection.</li>
* <li><b>afterAjax</b>: An array that contains one or more callbacks which
* will be executed after AJAX request is finishhed regrardless of status code.</li>
* </ul>
* @returns {AJAXRequest}
*/
function AJAXRequest(config = {
method: 'get',
url: '',
'verbose': false,
enabled: true,
beforeAjax: [],
onSuccess: [],
onClientErr: [],
onServerErr: [],
onDisconnected: [],
afterAjax: [],
onErr: [],
headers: {}
}) {
/**
* Any custom headers that will be sent with the request.
*/
this.customHeaders = {};
this.extras = {};
/**
* Request method.
*/
this.method = 'GET';
/**
* An array that holds objects which will be binded with callbacks.
*/
this.bindParams = [];
/**
* The URL of AJAX request
*/
this.url = '';
/**
* The base URL which is used to send requests.
*/
this.base = null;
/**
* Any parameters to send with the request.
*/
this.params = '';
/**
* Enable or disable AJAX. used to ristrict access.
*/
this.enabled = true;
/**
* Server response after processing the request.
*/
this.serverResponse = null;
/**
* A callback function to call in case of file upload is completed.
* Similar to onreadystatechange.
* @returns {undefined}
*/
this.onload = function () { };
this.onprogress = function (e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.info('AJAXRequest: Uploaded ' + percentComplete + '%');
} else {
console.info('AJAXRequest: Not lengthComputable!');
}
};
/**
* A pool of functions to call in case of internet connection lost.
*/
this.onconnectionlostpool = [
{
id: '0',
call: true,
pool:'connectionlost',
func: function () {
console.info('AJAXRequest: Connection lost. Status: ' + this.status);
}
}
];
/**
* A pool of functions to call before ajax request is sent.
*/
this.onbeforeajaxpool = [
{
id: '0',
call: true,
pool:'beforeajax',
func: function () {
console.info('AJAXRequest: Executing Before AJAX callbacks.');
}
}
];
/**
* A pool of functions to call after ajax has finished with regards of the
* final state.
*/
this.onafterajaxpool = [
{
id: '0',
call: true,
pool:'afterajax',
func: function () {
console.info('AJAXRequest: After AJAX ' + this.status);
}
}
];
/**
* A pool of functions to call in case one of the functions in the
* instance thrown an exception.
*/
this.onerrorpool = [
{
id: '0',
call: true,
pool:'error',
func: function () {
console.info('AJAXRequest: Error in one of the callbacks.');
}
}
];
/**
* A pool of functions to call in case of successful request.
*/
this.onsuccesspool = [
{
id: '0',
call: true,
pool:'success',
func: function () {
console.info('AJAXRequest: Success ' + this.status);
}
}
];
/**
* A pool of functions to call in case of server error.
*/
this.onservererrorpool = [
{
id: '0',
call: true,
pool:'ervererror',
func: function () {
console.info('AJAXRequest: Server Error ' + this.status);
}
}
];
/**
* A pool of functions to call in case of client error.
*/
this.onclienterrorpool = [
{
id: '0',
call: true,
pool:'clienterror',
func: function () {
console.info('AJAXRequest: Client Error ' + this.status);
}
}
];
this.retry = {
times:3,
passed:0,
wait:5,
pass_number:0,
func: function () {
}
},
Object.defineProperty(this, 'onreadystatechange', {
value: function () {
if (this.readyState === 0) {
this.log('AJAXRequest: Ready State = 0 (UNSENT)', 'info');
} else if (this.readyState === 1) {
this.log('AJAXRequest: Ready State = 1 (OPENED)', 'info');
} else if (this.readyState === 2) {
this.log('AJAXRequest: Ready State = 2 (HEADERS_RECEIVED)', 'info');
} else if (this.readyState === 3) {
this.log('AJAXRequest: Ready State = 3 (LOADING)', 'info');
} else if (this.readyState === 4 && this.status === 0) {
this.log('AJAXRequest: Ready State = 4 (DONE)', 'info');
if (this.retry.times !== 0 && this.retry.pass_number < this.retry.times) {
this.log('AJAXRequest: Retry after '+this.retry.wait+' seconds...', 'info');
var i = this;
this.retry.id = setInterval(function () {
i.retry.passed++;
i.retry.func(i.retry.wait - i.retry.passed, i.retry.pass_number);
if (i.retry.passed === i.retry.wait) {
clearInterval(i.retry.id);
i.retry.passed = 0;
i.retry.pass_number++;
i.AJAXRequest.send();
}
}, 1000);
} else {
this.retry.pass_number = 0;
setProbsAfterAjax(this, 'connectionlost');
}
} else if (this.readyState === 4 && this.status >= 200 && this.status < 300) {
this.log('AJAXRequest: Ready State = 4 (DONE).', 'info');
setProbsAfterAjax(this, 'success');
} else if (this.readyState === 4 && this.status >= 400 && this.status < 500) {
this.log('AJAXRequest: Ready State = 4 (DONE).', 'info');
setProbsAfterAjax(this, 'clienterror');
} else if (this.readyState === 4 && this.status >= 300 && this.status < 400) {
this.log('AJAXRequest: Ready State = 4 (DONE).', 'info');
this.log('Redirect', 'info', true);
setProbsAfterAjax(this, 'success');
} else if (this.readyState === 4 && this.status >= 500 && this.status < 600) {
this.log('AJAXRequest: Ready State = 4 (DONE).', 'info');
setProbsAfterAjax(this, 'servererror');
} else if (this.readyState === 4) {
this.active = false;
this.log('Status: ' + this.status, 'info');
}
},
writable: false,
enumerable: false
});
function canCall(funcObj) {
var canCall = funcObj.call === true;
var type = typeof funcObj.call;
if (type === 'function') {
canCall = funcObj.call();
}
return canCall;
}
function bindParams(funcObj, ajaxRequest) {
var bindObj = {};
for (var x = 0 ; x < ajaxRequest.bindParams.length ; x++) {
var objProps = ajaxRequest.bindParams[x];
if (objProps.pools.indexOf(funcObj.pool) !== -1) {
var keys = Object.keys(objProps.params);
for (var y = 0 ; y < keys.length ; y++) {
bindObj[keys[y]] = objProps.params[keys[y]];
}
}
}
funcObj.props = bindObj;
}
function callOnErr(inst, jsonResponse, headers, e) {
inst.log('AJAXRequest: An error occurred while executing the callback at "' + e.fileName + '" line ' + e.lineNumber + '. Check Below for more details.', 'error', true);
inst.log(e, 'error', true);
for (var i = 0; i < inst.onerrorpool.length; i++) {
try {
bindParams(inst.onerrorpool[i], inst);
if (canCall(inst.onerrorpool[i])) {
inst.log('AJAXRequest: Callback ' + inst.onerrorpool[i].id + ' is enabled.', 'info');
inst.onerrorpool[i].AJAXRequest = inst;
inst.onerrorpool[i].e = e;
inst.onerrorpool[i].status = inst.status;
inst.onerrorpool[i].response = inst.responseText;
inst.onerrorpool[i].xmlResponse = inst.responseXML;
inst.onerrorpool[i].jsonResponse = jsonResponse;
inst.onerrorpool[i].responseHeaders = headers;
inst.onerrorpool[i].func();
} else {
inst.log('AJAXRequest: Callback "' + inst.onerrorpool[i].id + '" is disabled.', 'warning');
}
} catch (e) {
inst.log('AJAXRequest: An error occurred while executing the callback at "' + e.fileName + '" line ' + e.lineNumber + '. Check Below for more details.', 'error', true);
inst.log(e, 'error', true);
}
}
}
function setProbsAfterAjax(xhr, pool_name) {
//xhr is of type XMLHTTPRequest
xhr.received = true;
var headers = getResponseHeadersObj(xhr);
var p = 'on' + pool_name + 'pool';
try {
var jsonResponse = JSON.parse(xhr.responseText);
} catch (e) {
xhr.log('AJAXRequest: Unable to convert response into JSON object.', 'warning', true);
xhr.log('AJAXRequest: "jsonResponse" is set to \'null\'.', 'warning', true);
var jsonResponse = null;
}
for (var i = 0; i < xhr[p].length; i++) {
xhr[p][i].url = xhr.url;
xhr[p][i].base = xhr.base;
xhr[p][i].requestUrl = xhr.requestUrl;
xhr[p][i].status = xhr.status;
xhr[p][i].response = xhr.responseText;
xhr[p][i].xmlResponse = xhr.responseXML;
xhr[p][i].jsonResponse = jsonResponse;
xhr[p][i].responseHeaders = getResponseHeadersObj(xhr);
try {
bindParams(xhr[p][i], xhr.AJAXRequest);
if (canCall(xhr[p][i])) {
xhr.log('AJAXRequest: Callback "' + xhr[p][i].id + '" is enabled.', 'info');
xhr[p][i].func();
} else {
xhr.log('AJAXRequest: Callback "' + xhr[p][i].id + '" is disabled.', 'warning');
}
} catch (e) {
callOnErr(xhr, jsonResponse, headers, e);
}
}
for (var i = 0; i < xhr.onafterajaxpool.length; i++) {
xhr.onafterajaxpool[i].status = xhr.status;
xhr.onafterajaxpool[i].response = xhr.responseText;
xhr.onafterajaxpool[i].xmlResponse = xhr.responseXML;
xhr.onafterajaxpool[i].jsonResponse = jsonResponse;
xhr.onafterajaxpool[i].responseHeaders = headers;
try {
bindParams(xhr.onafterajaxpool[i], xhr.AJAXRequest);
if (canCall(xhr.onafterajaxpool[i])) {
xhr.log('AJAXRequest: Callback "' + xhr.onafterajaxpool[i].id + '" is enabled.', 'info');
xhr.onafterajaxpool[i].func();
} else {
xhr.log('AJAXRequest: Callback "' + xhr.onafterajaxpool[i].id + '" is disabled.', 'warning');
}
} catch (e) {
callOnErr(xhr, jsonResponse, headers, e);
}
}
xhr.active = false;
xhr.log('AJAXRequest: Finished AJAX Request.', 'info');
}
/**
* This function will extract response headers from the response.
* @returns {Object} The function will return response headers as an object.
* The keys of the object are headers names and the values are headers values.
* @param {Object} xhr The XMLHttpRequest object that the headers will be
* extracted from.
*/
function getResponseHeadersObj(xhr) {
var retVal = {};
var headersArr = xhr.getAllResponseHeaders().split("\r\n");
for (var x = 0; x < headersArr.length; x++) {
var fullHeader = headersArr[x];
var key = fullHeader.substring(0, fullHeader.indexOf(':'));
if (key.length > 0) {
retVal[key] = fullHeader.substring(fullHeader.indexOf(':') + 1).trim();
}
}
return retVal;
}
/**
* A utility function used to show warning in the console about the existance
* of events pool.
* @param {String} p_name The name of the pool.
* @returns {undefined}
*/
function noSuchPool(p_name) {
console.warn('No such bool: ' + p_name);
var pools = '';
for (var x = 0; x < AJAXRequest.CALLBACK_POOLS.length; x++) {
if (x === AJAXRequest.CALLBACK_POOLS.length - 1) {
pools += ' or ' + AJAXRequest.CALLBACK_POOLS[x];
} else {
if (x === AJAXRequest.CALLBACK_POOLS.length - 2) {
pools += AJAXRequest.CALLBACK_POOLS[x];
} else {
pools += AJAXRequest.CALLBACK_POOLS[x] + ', ';
}
}
}
console.info('Pool name must be one of the following: ' + pools);
}
Object.defineProperties(this, {
isEnabled: {
/**
* Checks if AJAX is enabled or disabled.
* @returns {Boolean} True if enabled and false if disabled.
*/
value: function () {
return this.enabled;
},
writable: false,
enumerable: true
},
getCallbacksIDs: {
/**
* Returns the IDs of all added callbacks.
*
* @param {String} poolName If specified, only the IDs of callbacks in the selected pool will be
* returned.
*
* @returns {Object|Array} If the pool name is not provided, the method will return an object. The
* properties of the object are pools names and the value of each property is an array that
* contains the IDs of callbacks in the pool. If pool name is given, the method will return an
* array that contains the IDs of callbacks in the specified pool.
*/
value: function (poolName = null) {
var retVal = {};
if (AJAXRequest.CALLBACK_POOLS.indexOf(poolName) !== -1) {
retVal = [];
var p = 'on' + poolName + 'pool';
for (var y = 0; y < this[p].length; y++) {
retVal.push(this[p][y].id);
}
return retVal;
} else if (poolName === null) {
for (var x = 0; x < AJAXRequest.CALLBACK_POOLS.length; x++) {
var poolName = AJAXRequest.CALLBACK_POOLS[x];
if (retVal[poolName] === undefined) {
retVal[poolName] = [];
}
var p = 'on' + poolName + 'pool';
for (var y = 0; y < this[p].length; y++) {
retVal[poolName].push(this[p][y].id);
}
}
}
return retVal;
},
writable: false,
enumerable: true
},
getBase: {
/**
* Returns the value of the base URL which is used to send AJAX requests.
*
* @returns {String|null} If the base is set, the method will return its value.
* If not, the method will return the value of the attribute 'href' of the
* 'base' tag. Other than that, null is returned.
*/
value: function () {
return this.base;
},
writable: false,
enumerable: true
},
bind: {
/**
* Binds a variable to a callback.
*
* Note that this method will override any existing bindings and bind with the
* new provided object.
*
* @param {Object} obj An object that contains the variables that will be binded.
*
* @param {String|null} callbackId Optional callback ID. If Specified, the variable will
* only binded with callbacks having provided ID.
*
* @param {String|null} poolName An optional pool name. If specified, the variable will
* only be binded to the callbacks in the given pool. Possible values for the parameter
* must be taken from the array AJAXRequest.CALLBACK_POOLS.
*
* @returns {undefined}
*/
value: function (obj, callbackId = null, poolName = null) {
if (obj === null || obj === undefined || typeof obj !== 'object') {
this.log('AJAXRequest.bind: Provided object is invalid.', 'warning');
return;
}
this.log('AJAXRequest.bind: Callback ID = "' + callbackId + '"', 'info');
this.log('AJAXRequest.bind: Pool = "' + poolName + '"', 'info');
var applicablePools = [];
if (callbackId === null || callbackId === undefined) {
this.log('AJAXRequest.bind: The binding will be for all callbacks.', 'warning');
var cId = 'ALL';
} else {
var cId = callbackId + '';
this.log('AJAXRequest.bind: The binding will be for callbacks with given ID.', 'info');
}
if (poolName === null || poolName === undefined) {
this.log('AJAXRequest.bind: The binding will be for all pools.', 'warning');
applicablePools = AJAXRequest.CALLBACK_POOLS;
} else {
if (AJAXRequest.CALLBACK_POOLS.indexOf(poolName) === -1) {
this.log('AJAXRequest.bind: No such pool: ""' + poolName + '.', 'warning');
return;
}
this.log('AJAXRequest.bind: The binding will be for callbacks in the specified pool.', 'info');
applicablePools.push(poolName);
}
this.bindParams.push({
pools:applicablePools,
callbackId:callbackId,
params:obj
});
},
writable: false,
enumerable: true
},
setBase: {
/**
* Updates the value of the base URL which is used to send AJAX requests.
*
* @param {String|null} base The value of the new base URL. Only set if given URL is
* valid.
*/
value: function (base) {
if (base === null || base === undefined || base.trim().length === 0) {
this.base = null;
this.log('AJAXRequest.setBase: Base is set to "null".');
return;
}
base = base.trim();
if (AJAXRequest.isValidURL(base)) {
while (base[base.length - 1] === '/') {
base = base.substring(0, base.length - 1);
}
this.base = base;
this.log('AJAXRequest.setBase: Base is set to "' + this.getBase() + '".', 'info');
} else {
this.log('AJAXRequest.setBase: Base not updated.', 'warning');
}
},
writable: false,
enumerable: true
},
log: {
/**
* Shows a message in the browser's console.
* @param {String} message The message to display.
* @param {String} type The type of the message. It can be 'info',
* 'error' or 'warning'.
* @param {boolean} force If set to true, the message will be shown
* even if the logging is disabled.
*/
value: function (message, type = '', force = false) {
if (this.verbose === true || force === true) {
if (type === 'info') {
console.info(message);
} else if (type === 'warning') {
console.warn(message);
} else if (type === 'error') {
console.error(message);
} else {
console.log(message);
}
}
},
writable: false,
enumerable: true
},
setResponse: {
/**
* Sets the value of the property serverResponse. Do not call this function
* manually.
* @param {String} response
* @returns {undefined}
*/
value: function (response) {
this.serverResponse = response;
this.log('AJAXRequest.setResponse: Response updated.', 'info');
},
writable: false,
enumerable: true
},
getServerResponse: {
/**
* Return the value of the property serverResponse. Call this function after
* any complete AJAX request to get response load in case there is a load.
* @returns {String}
*/
value: function () {
return this.serverResponse;
},
writable: false,
enumerable: true
},
responseAsJSON: {
/**
* Return a JSON representation of response payload in case it can be convirted
* into JSON object. Else, in case the payload cannot be convirted, it returns
* undefined.
* @returns {Object|undefined}
*/
value: function () {
try {
return JSON.parse(this.getServerResponse());
} catch (e) {
this.log('AJAXRequest.responseAsJSON: Unable to convert server response to JSON object!', 'warning', true);
}
return undefined;
},
writable: false,
enumerable: true
},
addCallback: {
/**
*
* @param {Function|Object} callback A function to call. This also can be an object.
* The object can have following properties, 'callback' The function that will be executed.
* 'id': A unique itentifier for the callback.
* 'call': a boolean or function that evaluate to a boolean. Used to decide if the
* callback will be executed or not. 'props' Extra properties that the developer would like
* to have passed in the callback. Accessed using the keyword 'this' in the body of the
* callback.
*
* @param {String} poolName The name of the pool at which the callback will be added to.
* Must be a value from the array AJAXRequest.CALLBACK_POOLS.
*
* @returns {undefined|String} Returns an ID for the function. If not added,
* the method will return undefined.
*/
value: function (callback, poolName) {
var inst = this;
var pool_name = poolName.toLowerCase();
this.log('AJAXRequest.addCallback: Adding new callback to the pool "' + pool_name + '"...', 'info');
if (AJAXRequest.CALLBACK_POOLS.indexOf(pool_name) !== -1) {
var p = 'on' + pool_name + 'pool';
var callType = typeof callback;
var id = this[p].length + '';
if (callType === 'function') {
this.log('AJAXRequest.addCallback: Callback given as function.', 'info');
this[p].push({ AJAXRequest: inst, id: id, call: true, func: callback, pool:poolName });
this.log('AJAXRequest.addCallback: New callback added [id = "' + id + '"].', 'info');
return id;
} else if (callType === 'object') {
this.log('AJAXRequest.addCallback: Callback given as an object.', 'info');
if (typeof callback.callback === 'function') {
this.log('AJAXRequest.addCallback: Property "callback" is set.', 'info');
var toAdd = {
func: callback.callback,
AJAXRequest: inst,
pool:poolName,
}
var typeOfId = typeof callback.id;
if (typeOfId === 'undefined' || callback.id === null) {
this.log('AJAXRequest.addCallback: Property "id" is not set. Using generated ID.', 'warning');
toAdd.id = id;
} else {
this.log('AJAXRequest.addCallback: Property "id" is set.', 'info');
toAdd.id = callback.id + '';
if (this.getCallbacksIDs(pool_name).indexOf(toAdd.id) !== -1) {
this.log('AJAXRequest.addCallback: Can\'t Add callback. A callback with ID "' + toAdd.id + '" was already added to the pool "' + poolName + '".', 'warning', true);
return;
}
id = toAdd.id;
}
if (typeof callback.call === 'boolean') {
this.log('AJAXRequest.addCallback: Property "call" is set as a boolean.', 'info');
toAdd.call = callback.call;
} else if (typeof callback.call === 'function') {
this.log('AJAXRequest.addCallback: Property "call" is set as a function.', 'info');
toAdd.call = callback.call;
} else {
this.log('AJAXRequest.addCallback: Property "call" is not set. Using "true" as default value.', 'warning');
toAdd.call = true;
}
this[p].push(toAdd);
this.log('AJAXRequest.addCallback: New callback added [id = "' + toAdd.id + '"].', 'info');
} else {
this.log('AJAXRequest.addCallback: Property "callback" is not set or invalid. Callback with ID "' + toAdd.id + '" was not added to the pool "' + poolName + '".', 'warning', true);
}
}
} else {
this.log('AJAXRequest.addCallback: No such pool: \'' + pool_name + '\'', 'error');
}
},
writable: false,
enumerable: true
},
setOnServerError: {
/**
* Append a function to the pool of functions that will be called in case of
* server error (code 5xx).
*
* @param {Function|Object} callback A function to call. This also can be an object.
* The object can have following properties, 'callback' The function that will be executed.
* 'id': A unique itentifier for the callback.
* 'call': a boolean or function that evaluate to a boolean. Used to decide if the
* callback will be executed or not. 'props' Extra properties that the developer would like
* to have passed in the callback. Accessed using the keyword 'this' in the body of the
* callback.
*
* @returns {undefined|String|Number} Returns an ID for the function. If not added,
* the method will return undefined.
*/
value: function (callback) {
return this.addCallback(callback, 'servererror');
},
writable: false,
enumerable: true
},
removeCall: {
/**
* Removes a callback function from a specific pool given its ID.
* @param {String} pool_name The name of the pool. It should be one of the
* values in the array AJAXRequest.CALLBACK_POOLS.
* @param {String} id The ID of the callback function.
* @returns {undefined}
*/
value: function (pool_name, id) {
id = id + '';
if (pool_name !== undefined && pool_name !== null) {
if (typeof pool_name === 'string') {
pool_name = pool_name.toLowerCase();
if (AJAXRequest.CALLBACK_POOLS.indexOf(pool_name) !== -1) {
pool_name = 'on' + pool_name + 'pool';
for (var x = 0; x < this[pool_name].length; x++) {
if (this[pool_name][x]['id'] === id) {
return this[pool_name].pop(this[pool_name][x]);
}
}
this.log('AJAXRequest.removeCall: No callback was found with ID = "' + id + '" in the pool \'' + pool_name + '\'', 'error');
} else {
noSuchPool(pool_name);
}
} else {
this.log('AJAXRequest.removeCall: Invalid pool name type. Pool name must be string.', 'error');
}
} else {
noSuchPool(pool_name);
}
},
writable: false,
enumerable: true
},
disableCallsExcept: {
value: function (id, call) {
for (var x = 0; x < AJAXRequest.CALLBACK_POOLS.length; x++) {
this.disableCallExcept(AJAXRequest.CALLBACK_POOLS[x], id);
}
},
writable: false,
enumerable: true
},
disableCallExcept: {
/**
* Disable all callback functions except the one that its ID is given.
* @param {String} pool_name The name of the pool. It should be a value from
* the array AJAXRequest.CALLBACK_POOLS.
* @param {String} id The ID of the function that was provided when the function
* was added to the pool. If the ID does not exist, All callbacks will be disabled.
* @returns {undefined}
*/
value: function (pool_name, id = -1) {
id = id + '';
if (pool_name !== undefined && pool_name !== null) {
if (typeof pool_name === 'string') {
pool_name = pool_name.toLowerCase();
if (AJAXRequest.CALLBACK_POOLS.indexOf(pool_name) !== -1) {
pool_name = 'on' + pool_name + 'pool';
for (var x = 0; x < this[pool_name].length; x++) {
//first two IDs are reserved. do not disable.
if (this[pool_name][x]['id'] !== id && this[pool_name][x]['id'] > 1) {
this[pool_name][x]['call'] = false;
} else {
this[pool_name][x]['call'] = true;
}
}
return;
} else {
noSuchPool(pool_name);
}
} else {
this.log('AJAXRequest.disableCallExcept: Invalid pool name type. Pool name must be string.', 'error');
}
} else {
noSuchPool(pool_name);
}
},
writable: false,
enumerable: true
},
setCallsEnabled: {
/**
* Enable or disable a callbacks with same ID in all pools given the ID.
*
* @param {String|Number} id The ID that was set for all callbacks.
*
* @param {Boolean|Function} call This can be a boolean or can be a function that evaluate
* to a boolean.
*/
value: function (id, call) {
for (var x = 0; x < AJAXRequest.CALLBACK_POOLS.length; x++) {
this.setCallEnabled(AJAXRequest.CALLBACK_POOLS[x], id, call);
}
},
writable: false,
enumerable: true
},
setCallEnabled: {
/**
* Enable or disable a callback on specific pool.
* @param {String} pool_name The name of the pool. It must be one of the
* values in the aray AJAXRequest.CALLBACK_POOLS.
*
* @param {String} id The ID of the callback. It is given when the callback
* was added.
*
* @param {Boolean} call If set to true, the function will be called. Else
* if it is set to false, it will be not called.
*/
value: function (pool_name, id, call) {
id = id + ''
if (pool_name !== undefined && pool_name !== null) {
if (typeof pool_name === 'string') {
pool_name = pool_name.toLowerCase();
this.log('AJAXRequest.setCallEnabled: Checking if pool "' + pool_name + '" exist...', 'info')
if (AJAXRequest.CALLBACK_POOLS.indexOf(pool_name) !== -1) {
pool_name = 'on' + pool_name + 'pool';
for (var x = 0; x < this[pool_name].length; x++) {
if (this[pool_name][x]['id'] === id) {
this[pool_name][x]['call'] = call;
this.log('AJAXRequest.setCallEnabled: Callback status updated.', 'info');
return;
}
}
this.log('AJAXRequest.setCallEnabled: No callback was found with ID = "' + id + '" in the pool \'' + pool_name + '\'', 'warning');
} else {
noSuchPool(pool_name);
}
} else {
this.log('AJAXRequest.setCallEnabled: Invalid pool name type. Pool name must be string.', 'error');
}
} else {
noSuchPool(pool_name);
}
},
writable: false,
enumerable: true
},
getCallBack: {
/**
* Returns an object that contains the information of a callback function.
* @param {type} pool_name The name of the pool. It must be in the array
* AJAXRequest.CALLBACK_POOLS.
* @param {String} id The ID of the callback.
* @returns {Object|undefined} Returns an object that contains the
* information of the callback. If it is not found, or the pool name is invalid,
* the method will show a warning in the console and returns undefined.
*/
value: function (pool_name, id) {