kreta/KretaWeb/Scripts/AjaxHelper.js
2024-03-13 00:33:46 +01:00

878 lines
21 KiB
JavaScript

var AjaxHelper = (function () {
var ajaxHelper = function () {};
var postedUrlAndButtonId = ['', ''];
ajaxHelper.ProgresUrl = '';
ajaxHelper.AsyncPingPost = function (url, successCallBack) {
asyncPingPost(url, successCallBack);
};
ajaxHelper.AsyncPost = function (
url,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
doRequest(
url,
true,
data,
undefined,
'POST',
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
};
ajaxHelper.AsyncGet = function (
url,
data,
successCallBack,
errorCallBack,
completeCallBack
) {
doRequest(
url,
true,
data,
undefined,
'GET',
successCallBack,
errorCallBack,
completeCallBack
);
};
ajaxHelper.DoAsyncValidationPost = function (
url,
element,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
doValidationPost(
url,
true,
element,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
};
ajaxHelper.DoPost = function (
url,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
doRequest(
url,
true,
data,
undefined,
'POST',
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
};
ajaxHelper.DoPostQuery = function (
url,
data,
query,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
doRequest(
url,
true,
data,
query,
'POST',
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
};
ajaxHelper.DoPostElement = function (
url,
element,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
doPostElement(
url,
true,
element,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
};
ajaxHelper.DoValidationPost = function (
url,
element,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
doValidationPost(
url,
true,
element,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
};
ajaxHelper.DoGet = function (
url,
data,
successCallBack,
errorCallBack,
completeCallBack
) {
doRequest(
url,
true,
undefined,
data,
'GET',
successCallBack,
errorCallBack,
completeCallBack
);
};
ajaxHelper.ShowIndicator = function () {
showLoadingIndicator();
};
ajaxHelper.HideIndicator = function () {
hideLoadingIndicator();
};
ajaxHelper.RemoteErrors = function (jForm, errors) {
remoteErrors(jForm, errors);
};
ajaxHelper.CallRemoteErrors = function (formName, modelState) {
remoteErrors(formName, modelState);
};
ajaxHelper.ShowError = function (responseJSON) {
showErrorOrReportError(responseJSON);
};
function doRequest(
url,
isAsync,
data,
query,
requestType,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
if (!CommonUtils.isUndefined(query)) {
url = url + '?' + $.param(query);
}
var jsonData = null;
if (data != null) {
jsonData = JSON.stringify(data);
}
ajaxRequest(
url,
isAsync,
jsonData,
requestType,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
}
function doPostElement(
url,
isAsync,
element,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
element = $('#' + element);
removeValidatonSummaryClass(element);
if (element.valid()) {
var data = element.toObject();
$.each(element.find('[id$=ModelForm]'), function () {
if (!CommonUtils.isNullOrUndefined($(this))) {
data[$(this).attr('id').replace('ModelForm', 'Model')] =
$(this).toObject();
}
});
var jsonData = JSON.stringify(data);
ajaxValidationPost(
url,
isAsync,
element,
jsonData,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
}
}
function doValidationPost(
url,
isAsync,
element,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
element = $('#' + element);
$.each(element.find('[id$=ModelForm]'), function () {
if (!CommonUtils.isNullOrUndefined($(this))) {
data[$(this).attr('id').replace('ModelForm', 'Model')] =
$(this).toObject();
}
});
var jsonData = JSON.stringify(data);
ajaxValidationPost(
url,
isAsync,
element,
jsonData,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
);
}
function ajaxValidationPost(
url,
isAsync,
element,
data,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
if (!CommonUtils.isNullOrUndefined(buttonId)) {
if (
postedUrlAndButtonId.find(
(element) => element.Url == url && element.ButtonId == buttonId
) != undefined
) {
return;
} else {
postedUrlAndButtonId.push({ Url: url, ButtonId: buttonId });
}
}
var csrfToken = $("input[name='__RequestVerificationToken']").val();
$.ajax({
type: 'POST',
headers: { 'X-Request-Verification-Token': csrfToken },
url: url,
data: data,
async: isAsync,
cache: false,
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
try {
clearErrors(element);
callDelegateAjaxMethod(successCallBack, data);
} catch (e) {
logConsolError(e);
}
},
error: function (response) {
errorValidationHandler(response, element, errorCallBack);
},
complete: function () {
if (!CommonUtils.isNullOrUndefined(buttonId)) {
var aktivUrlButtonId = [url, buttonId];
postedUrlAndButtonId.splice(
postedUrlAndButtonId.indexOf(aktivUrlButtonId),
1
);
}
try {
callDelegateAjaxMethodComplete(completeCallBack);
checkTimeOut();
} catch (e) {
logConsolError(e);
}
}
});
}
function asyncPingPost(url, successCallBack) {
var csrfToken = $("input[name='__RequestVerificationToken']").val();
$.ajax({
type: 'POST',
headers: { 'X-Request-Verification-Token': csrfToken },
url: url,
async: true,
cache: false,
global: false,
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
try {
callDelegateAjaxMethod(successCallBack, data);
} catch (e) {
logConsolError(e);
}
}
});
}
function ajaxRequest(
url,
isAsync,
data,
requestType,
successCallBack,
errorCallBack,
completeCallBack,
buttonId
) {
if (!CommonUtils.isNullOrUndefined(buttonId)) {
if (
postedUrlAndButtonId.find(
(element) => element.Url == url && element.ButtonId == buttonId
) != undefined
) {
return;
} else {
postedUrlAndButtonId.push({ Url: url, ButtonId: buttonId });
}
}
var csrfToken = $("input[name='__RequestVerificationToken']").val();
$.ajax({
type: requestType,
headers: { 'X-Request-Verification-Token': csrfToken },
url: url,
data: data,
async: isAsync,
cache: false,
datatype: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
try {
callDelegateAjaxMethod(successCallBack, data);
} catch (e) {
logConsolError(e);
}
},
error: function (response) {
errorHandler(response, errorCallBack);
},
complete: function () {
if (!CommonUtils.isNullOrUndefined(buttonId)) {
var aktivUrlButtonId = [url, buttonId];
postedUrlAndButtonId.splice(
postedUrlAndButtonId.indexOf(aktivUrlButtonId),
1
);
}
try {
callDelegateAjaxMethodComplete(completeCallBack);
checkTimeOut();
} catch (e) {
logConsolError(e);
}
}
});
}
function errorHandler(response, errorCallBack) {
try {
if (CommonUtils.isFunction(errorCallBack)) {
errorCallBack(response);
return;
}
if (response.status == 491 /*WarningMegszakitas*/) {
if (typeof response.responseJSON.Json !== 'undefined') {
remoteServerWarrning(response.responseJSON.Json);
return;
}
}
showErrorOrReportError(response);
} catch (e) {
logConsolError(e);
}
}
function errorValidationHandler(response, element, errorCallBack) {
try {
if (response.status == 491 /*WarningMegszakitas*/) {
if (typeof response.responseJSON.Json !== 'undefined') {
remoteServerWarrning(response.responseJSON.Json);
return;
}
}
if (!CommonUtils.isNullOrUndefined(response.responseJSON.ModelState)) {
remoteErrors(element, response.responseJSON.ModelState);
}
if (!CommonUtils.isNullOrUndefined(response.responseJSON.MVCModelState)) {
mvcRemoteErrors(element, response.responseJSON.MVCModelState);
}
if (CommonUtils.isFunction(errorCallBack)) {
errorCallBack(response);
return;
}
if (response.responseJSON.ErrorCode) {
showReportError(response.responseJSON);
} else {
// ha bármilyen modelstate error van, akkor az alert error nem kell
if (
CommonUtils.isNullOrUndefined(response.responseJSON.ModelState) &&
CommonUtils.isNullOrUndefined(response.responseJSON.MVCModelState)
) {
if (CommonUtils.isNullOrUndefined(response.responseJSON.ModelState))
var closeFuntion = undefined;
if (response.responseJSON.CloseFunction) {
closeFuntion = new Function(response.responseJSON.CloseFunction);
}
showError(response.responseJSON.Message, closeFuntion);
}
}
} catch (e) {
logConsolError(e);
}
}
function callDelegateAjaxMethod(callBack, data) {
if (CommonUtils.isFunction(callBack)) {
callBack(data);
}
}
function callDelegateAjaxMethodComplete(callBack) {
if (CommonUtils.isFunction(callBack)) {
callBack();
}
}
function checkTimeOut() {
if (!SessionHandler) {
SessionHandler.Start();
}
}
function showLoadingIndicator() {
var progress = $('#KretaProgressBar');
if (progress) {
var highest = 10000;
$('body')
.children()
.each(function () {
var current = parseInt($(this).css('z-index'), 10);
if (current && highest < current) highest = current;
});
progress.css('z-index', highest + 1);
progress.show();
progress.addClass('isOverlayActiv');
$('input:submit').each(function () {
$(this).addClass('disabledInputOnSubmit');
$(this).prop('disabled', true);
});
$('button').each(function () {
var button = $(this).data('kendoButton');
if (typeof button !== 'undefined') {
if ($(this).addClass('ignore-ajaxhelper') == false) {
$(this).addClass('disabledKendoButtonOnSubmit');
button.enable(false);
}
}
});
}
}
function hideLoadingIndicator() {
var progress = $('#KretaProgressBar');
if (progress) {
progress.hide();
progress.removeClass('isOverlayActiv');
$('.disabledInputOnSubmit').each(function () {
$(this).prop('disabled', false);
$(this).removeClass('disabledInputOnSubmit');
});
$('.disabledKendoButtonOnSubmit').each(function () {
var button = $(this).data('kendoButton');
if (
typeof button !== 'undefined' &&
$(this).addClass('ignore-ajaxhelper') == false
) {
button.enable(true);
}
$(this).removeClass('disabledKendoButtonOnSubmit');
});
}
}
function mvcRemoteErrors(jForm, errors) {
function handleInput(id, error) {
var toApply = function () {
var control = $('#' + id);
var label = $('label[for="' + id + '"]');
control.attr('title', getEncodedTextWithLineBreak(error));
label.addClass('labelError');
};
setTimeout(toApply, 0);
}
jForm.find('.labelError').removeClass('labelError');
jForm.find('.field-validation-error').remove();
var container = jForm.find('.kreta-validation-summary');
var list = container.find('ul');
list.empty();
container
.addClass('validation-summary-valid')
.removeClass('validation-summary-errors');
$('.kreta-validation-summary').css({ display: 'none' });
$.each(errors, function (i, error) {
var errorData =
"<label id='" +
error.Key +
i +
"-error' class='error labelError' for='" +
error.Key +
"'>" +
getEncodedTextWithLineBreak(error.Message) +
'</label>';
$('<li />').html(errorData).appendTo(list);
handleInput(error.Key, error.Message);
});
container
.addClass('validation-summary-errors')
.removeClass('validation-summary-valid');
$('.kreta-validation-summary').css({ display: 'block' });
}
function remoteErrors(jForm, errors) {
function handleInput(name, error) {
var toApply = function () {
for (var i = 0; i < error.length; i++) {
var errorMessage = error[i];
name = name.replace(/^model\./g, '');
var id = name.replace(/\./g, '_');
var control = $('#' + id);
var label = $('label[for="' + name + '"]');
control.attr('title', getEncodedTextWithLineBreak(errorMessage));
label.addClass('labelError');
}
};
setTimeout(toApply, 0);
}
jForm.find('.labelError').removeClass('labelError');
jForm.find('.field-validation-error').remove();
var container = jForm.find('.kreta-validation-summary');
var list = container.find('ul');
list.empty();
container
.addClass('validation-summary-valid')
.removeClass('validation-summary-errors');
$('.kreta-validation-summary').css({ display: 'none' });
$.each(errors, function (name, error) {
if (error && error.length > 0) {
$.each(error, function (i, ival) {
var modelName;
var splittedStringLength = name.split('.').length;
if (splittedStringLength == 2) {
modelName = name.replace(name.slice(0, name.indexOf('.') + 1), '');
} else if (splittedStringLength > 2) {
modelName = name
.replace(name.slice(0, name.indexOf('.') + 1), '')
.replace('.', '_');
} else {
modelName = name;
}
var errorData =
"<label id='" +
modelName +
"-error' class='error labelError' for='" +
modelName +
"'>" +
getEncodedTextWithLineBreak(ival) +
'</label>';
$('<li />').html(errorData).appendTo(list);
});
container
.addClass('validation-summary-errors')
.removeClass('validation-summary-valid');
$('.kreta-validation-summary').css({ display: 'block' });
handleInput(name, error);
}
});
}
function clearErrors(jForm) {
remoteErrors(jForm, []);
}
function remoteServerWarrning(warning) {
var closeFuntion = undefined;
if (warning.CloseFunction) {
closeFuntion = new Function(warning.CloseFunction);
}
KretaWindowHelper.confirmWindow(
Globalization.Figyelem,
warning.Msg,
new Function(warning.SuccessFunction),
null,
closeFuntion,
Globalization.Folytatas,
Globalization.Megsem
);
}
function getEncodedTextWithLineBreak(text) {
return kendo
.htmlEncode(text)
.replaceAll(kendo.htmlEncode('<br>'), '<br />')
.replaceAll(kendo.htmlEncode('<br />'), '<br />')
.replaceAll(kendo.htmlEncode('<br/>'), '<br />');
}
function showReportError(errorJson) {
if (errorJson.Message && errorJson.Message.length > 0) {
if (typeof KretaWindowHelper !== 'undefined') {
KretaWindowHelper.feedbackWindow(
Globalization.Hiba,
errorJson.Message.replace(CommonUtils.LineBreakRegex, '<br />'),
true
);
} else {
logConsolError(errorJson.Message);
}
}
}
function showError(error, closeFuntion) {
if (error && error.length > 0) {
if (typeof KretaWindowHelper !== 'undefined') {
KretaWindowHelper.feedbackWindow(
Globalization.Hiba,
error,
true,
closeFuntion
);
} else {
logConsolError(error);
}
}
}
function logConsolError(e) {
if (
typeof console !== 'undefined' &&
typeof console.error !== 'undefined'
) {
console.error(e);
}
}
function showErrorOrReportError(data) {
if (data.responseJSON) {
if (data.responseJSON.ErrorCode) {
showReportError(data.responseJSON);
} else {
if (data.responseJSON.Message) {
var closeFuntion = undefined;
if (data.responseJSON.CloseFunction) {
closeFuntion = new Function(data.responseJSON.CloseFunction);
}
showError(
data.responseJSON.Message.replace(
CommonUtils.LineBreakRegex,
'<br />'
),
closeFuntion
);
}
}
}
}
function removeValidatonSummaryClass(item) {
var container = item.find('.kreta-validation-summary');
if (container.length > 0) {
var list = container.find('ul');
list.empty();
}
}
ajaxHelper.DownloadFile = function (
url,
payload,
isGet,
scriptAfterAjaxCall
) {
ajaxHelper.ShowIndicator();
var method = isGet ? 'GET' : 'POST';
var csrfToken = $("input[name='__RequestVerificationToken']").val();
var options = {
method,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'X-Request-Verification-Token': csrfToken
}
};
if (payload) {
if (isGet) {
var query = Object.keys(payload)
.map(
(key) =>
encodeURIComponent(key) + '=' + encodeURIComponent(payload[key])
)
.join('&');
url += '?' + query;
} else {
Object.assign(options, { body: JSON.stringify(payload) });
}
}
fetch(url, options)
.then(function (response) {
if (!response.ok) {
response.json().then(function (json) {
ajaxHelper.HideIndicator();
if (json && json.Message) {
KretaWindowHelper.warningWindow('Hiba', json.Message);
}
if (typeof scriptAfterAjaxCall === 'function') {
scriptAfterAjaxCall();
}
});
} else {
if (response.redirected) {
ajaxHelper.HideIndicator();
if (typeof scriptAfterAjaxCall === 'function') {
scriptAfterAjaxCall();
}
window.location.href = response.url;
} else {
var realFileName = '';
var disposition = response.headers.get('content-disposition');
var fileNameMatch = /filename="?([^"]*?)"?(;|$)/g.exec(disposition);
if (fileNameMatch && fileNameMatch.length > 1) {
realFileName = decodeURIComponent(fileNameMatch[1]);
} else {
fileNameMatch =
/(?:.*filename\*|filename)=(?:([^'"]*)''|("))([^;]+)\2(?:[;`\n]|$)/g.exec(
disposition
);
if (fileNameMatch && fileNameMatch.length > 3) {
var realFileName = decodeURIComponent(fileNameMatch[3]);
}
}
if (realFileName) {
response.blob().then(function (blob) {
ajaxHelper.HideIndicator();
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = realFileName;
a.click();
a.remove();
if (typeof scriptAfterAjaxCall === 'function') {
scriptAfterAjaxCall();
}
});
} else {
ajaxHelper.HideIndicator();
if (typeof scriptAfterAjaxCall === 'function') {
scriptAfterAjaxCall();
}
}
}
}
})
.catch(function (err) {
ajaxHelper.HideIndicator();
if (typeof scriptAfterAjaxCall === 'function') {
scriptAfterAjaxCall();
}
logConsolError(err);
});
};
return ajaxHelper;
})();