Javascript wait until localization resources are pulled from server - javascript

I have the following Javascript code:
(function (document, window, $) {
'use strict';
var Site = window.Site;
var translations = [];
$(document).ready(function ($) {
translations = Site.getTranslations();
Site.run(); // glogal site setup
});
// Init function
// ------------------------
(function () {
$("#cbolanguage").change(function (e) {
// start ajax request
$.ajax({
url: url.switchLang,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ lang: e.target.value }),
dataType: "json",
success: function (data, textStatus, jqXHR) {
if (data.success) {
location.reload();
}
},
error: function (jqXHR, textStatus, errorThrown) {
}, complete: function () {
}
});
});
function init() {
$('#btn-login').click(function (e) {
e.preventDefault();
$('#form-login').data('formValidation').validate();
if (!$('#form-login').data('formValidation').isValid()) return;
});
init();
}
})();
// Validataion
// ------------------------
(function () {
$('#form-login').formValidation({
framework: "bootstrap",
icon: null,
fields: {
Login: {
validators: {
notEmpty: {
message: translations.text1 // NEED TO WAIT UNTIL THIS HAS A VALUE
}
}
},
Password: {
validators: {
notEmpty: {
message: translations.text1 // NEED TO WAIT UNTIL THIS HAS A VALUE
}
}
},
},
err: {
clazz: 'text-help'
},
row: {
invalid: 'has-error'
}
}).on('err.field.fv', function (e, data) {
data.fv.disableSubmitButtons(false);
})
.on('success.field.fv', function (e, data) {
data.fv.disableSubmitButtons(false);
});;
})();
})(document, window, jQuery);
In the document.ready() I call the function:
translations = Site.getTranslations();
This function code is:
getTranslations: function () {
var returnData = [];
// start ajax request
$.ajax({
url: appData.getTranslations,
type: 'POST',
contentType: 'application/json',
dataType: "json",
async: false, // SYNCRONOUS CALL
success: function (data, textStatus, jqXHR) {
if (data.success) {
returnData = data.data;
}
},
error: function (jqXHR, textStatus, errorThrown) {
}, complete: function () {
}
});
return returnData;
},
The problem that I have is that on my main javascript all the functions, including the form validation are executed without waiting for the translation object to get a value.
I need to wait for all my functions until the call to get the translation resources to finish.
Any clue?

You can promisify your 'getTranslations' function and use await where you are calling it.Like this :
getTranslations: function () {
// start ajax request
return new Promise((resolve,reject)=>{
$.ajax({
url: appData.getTranslations,
type: 'POST',
contentType: 'application/json',
dataType: "json",
async: false, // SYNCRONOUS CALL
success: function (data, textStatus, jqXHR) {
if (data.success) {
resolve(data.data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
}, complete: function () {
}
});
});
},
Now await this call in your document.ready() function.
(function (document, window, $) {
'use strict';
var Site = window.Site;
var translations = [];
$(document).ready(async function ($) {
translations = await Site.getTranslations();
//change your immediately invoked functions into named functions
// and call them here
initialisation();
validation();
Site.run(); // glogal site setup
});
// Init function
// ------------------------
function initialisation() {
$("#cbolanguage").change(function (e) {
// start ajax request
$.ajax({
url: url.switchLang,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ lang: e.target.value }),
dataType: "json",
success: function (data, textStatus, jqXHR) {
if (data.success) {
location.reload();
}
},
error: function (jqXHR, textStatus, errorThrown) {
}, complete: function () {
}
});
});
function init() {
$('#btn-login').click(function (e) {
e.preventDefault();
$('#form-login').data('formValidation').validate();
if (!$('#form-login').data('formValidation').isValid()) return;
});
init();
}
};
// Validataion
// ------------------------
function validation() {
$('#form-login').formValidation({
framework: "bootstrap",
icon: null,
fields: {
Login: {
validators: {
notEmpty: {
message: translations.text1 // NEED TO WAIT UNTIL THIS HAS A VALUE
}
}
},
Password: {
validators: {
notEmpty: {
message: translations.text1 // NEED TO WAIT UNTIL THIS HAS A VALUE
}
}
},
},
err: {
clazz: 'text-help'
},
row: {
invalid: 'has-error'
}
}).on('err.field.fv', function (e, data) {
data.fv.disableSubmitButtons(false);
})
.on('success.field.fv', function (e, data) {
data.fv.disableSubmitButtons(false);
});;
}
})(document, window, jQuery);

Related

Loader works only on the first ajax call

I want the loader to stay until the complete execution is complete and statement $("#xyzDiv").html(data) has been executed. Currently the loader gets hidden after the first ajax call. Even if i add "beforeSend: function () { $("#loader").show(); }" to GetDataList(), the loader is not staying.
$.ajax
({
type: "POST",
url: ajaxUrl,
data: dataObj,
beforeSend: function () { $("#loader").show(); },
success: function (data)
{
if (data.result)
{
GetDataList();
toastr.success(data.strMsg);
}
else
{
toastr.error(data.strMsg);
}
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
},
complete: function () { $("#loader").hide(); }
});
function GetDataList()
{
$.ajax
({
type: "Get",
url: ajaxUrl,
data: dataObj,
success: function (data)
{
$("#xyzDiv").html(data);
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
}
});
}

ReferenceError: response is not defined on autocomplete jquery ajax call in singleton design pattern

I am trying to implement jQuery autocomplete in my solution but I got an error ReferenceError: response is not defined
Here is my code
(function ($) {
$.SupportArticleObj = function (p) {
var SupportArticle = {
config: {
isPostBack: false,
async: false,
cache: false,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: { data: '' },
dataType: 'json',
baseURL: "Modules/SupportArticle/Services/SupportArticleWebService.asmx/",
url: "",
method: "",
ajaxCallMode: 0,
PortalID: PortalID,
UserModuleID: UserModuleID,
SecureToken: SecureToken,
UserName: UserName
},
init: function () {
$("#searchSupport").autocomplete({
source: function (request, response) {
searchTerm = request.term;
SupportArticle.getSearchData(searchTerm);
}
});
},
getSearchData: function (searchTearm) {
SupportArticle.config.method = "SearchSupportArticle";
SupportArticle.config.url = SupportArticle.config.baseURL + SupportArticle.config.method;
SupportArticle.config.data = JSON2.stringify({
searchTerm: searchTerm,
portalID: SupportArticle.config.PortalID,
userModuleID: SupportArticle.config.UserModuleID,
userName: SupportArticle.config.UserName,
secureToken: SupportArticle.config.SecureToken
});
SupportArticle.ajaxCall(SupportArticle.config);
},
ajaxSuccess: function (data) {
response(data);
},
ajaxFailure: function () {
jAlert('Somethings went wrong', 'Support Article');
},
ajaxCall: function (config) {
$.ajax({
type: SupportArticle.config.type,
contentType: SupportArticle.config.contentType,
cache: SupportArticle.config.cache,
url: SupportArticle.config.url,
data: SupportArticle.config.data,
dataType: SupportArticle.config.dataType,
success: SupportArticle.ajaxSuccess,
error: SupportArticle.ajaxFailure,
async: SupportArticle.config.async
});
}
};
SupportArticle.init();
};
$.fn.callSupportArticle = function (p) {
$.SupportArticleObj(p);
};
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
What I am trying to do here is, I am calling a webservice which will search the records on database and return as a list and I want to bind that list on textbox as a autocomplete. But the problem is while running the solution in browser I got an error ReferenceError: response is not defined.
I was trying http://www.c-sharpcorner.com/UploadFile/da55bf/Asp-Net-autocomplete-textbox-using-jquery-json-and-ajax/ as reference.
How can I solve the issue of ReferenceError: response is not defined
Write your script like below:
AutoDemoDataBase: function () {
$("#lytA_ctl29_txtSearchName").autocomplete({
source: function (request, response) {
var param = JSON.stringify({
userModuleID: UserModuleID,
portalID: autoComplete.config.portalId,
prefix: $("#lytA_ctl29_txtSearchName").val(),
userName: autoComplete.config.UserName,
secureToken: SageFrameSecureToken
});
$.ajax({
type: autoComplete.config.type,
contentType: autoComplete.config.contentType,
cache: autoComplete.config.cache,
url: autoComplete.config.baseURL + "GetNames",
data: param,
dataType: autoComplete.config.dataType,
async: autoComplete.config.async,
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (response) {
jAlert(response.responseText);
},
failure: function (response) {
jAlert(response.responseText);
}
});
},
select: function (e, i) {
$("#hfId").val(i.item.val);
$('#test').text(i.item.val);
},
minLength: 1
});
}
Your ajax success function is out of response scope.

Dropbox API: Sending Data Via Ajax to Controller

I am using the Dropbox API JavaScript Chooser and want to return the data from the response into my Controller
The Javascript Options for the Dropbox API
options = {
success: function (files) {
$.ajax({
url: '/FileTransfer/FileData',
type: "POST",
dataType: "json",
//data: JSON.stringify(files[0]),
data: files,
success: function (result) {}
});
},
cancel: function () {},
linkType: "preview",
multiselect: true
};
Controller Action
My controller action currently doesn't do anything at the moment but will eventually cache the output data into a model once i can get data to be passed into it, which is hence my problem.
public JsonResult FileData(string model)
{
return Json(new { success = true });
}
ADyson`s hints have helped me solve my problem, thank you
Altered code below, note the change to data: and then deserialised in the Controller
Javascript
options = {
success: function (files) {
$.ajax({
url: '/FileTransfer/FileData',
type: "POST",
dataType: "json",
data: { result : JSON.stringify(files) },
//data: files,
success: function (result) {
$("#FileList").load('/FileTransfer/Cloud');
console.log(result);
},
error : function (jQXHR, textStatus, errorThrown) {
//alert("An error occurred: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}
});
},
cancel: function () {},
linkType: "preview",
multiselect: true
};
Controller
public JsonResult FileData(string result)
{
var convertedResult = JsonConvert.DeserializeObject<List<DropboxFile>>(result);
CacheEntity(convertedResult);
return Json(new { success = true });
}
Refactored code following suggestion
Javascript
options = {
success: function (files) {
$.ajax({
url: '/FileTransfer/FileData',
type: "POST",
dataType: "json",
data: { result : files},
success: function (result) {
$("#FileList").load('/FileTransfer/Cloud');
},
error : function (jQXHR, textStatus, errorThrown) { }
});
},
cancel: function () {
},
linkType: "preview",
multiselect: true
};
Controller
public JsonResult FileData(List<DropboxFile> result)
{
CacheEntity(result);
return Json(new { success = true });
}

multiple chain of when() then() - defered object

I want to do a chain of $.when().then($when().then(...)) in jquery. I'm not used to the defered functions, first time using them.
I changed my code a bit my code to represent this situation:
function setenum(e)
{
return $.ajax({
url: SetPathUrl1(),
type: 'GET',
data: { isNew: e.isNew() },
contentType: 'application/json; charset=utf-8',
success: function (data, status, xhr) {
/*My stuff*/
},
error: function (xhr, status, error) {
/*My stuff*/
}
});
}
function setdropdown1(e)
{
return $.ajax({
url: SetPathUrl2(),
type: 'GET',
data: { isNew: e.isNew() },
contentType: 'application/json; charset=utf-8',
success: function (data, status, xhr) {
/*Fill my first ddl based on enum*/
},
error: function (xhr, status, error) {
/*My stuff*/
}
});
}
function setdropdown2(e)
{
return $.ajax({
url: SetPathUrl3(),
type: 'GET',
contentType: 'application/json; charset=utf-8',
success: function (data, status, xhr) {
/*Fill my second ddl based on enum*/
},
error: function (xhr, status, error) {
/*My stuff*/
}
});
}
function DoOtherStuff(e)
{
/**/
}
function MainNotWorking(ImportantModel)
{
$.when(setenum(ImportantModel))
.then(
$.when(setdropdown1(ImportantModel),setdropdown2(ImportantModel))
.then(
function () {
DoOtherStuff(e);
}
)
);
}
function MainWorking(ImportantModel)
{
$.when(setenum(ImportantModel),setdropdown1(ImportantModel),setdropdown2(ImportantModel))
.then(
function () {
DoOtherStuff(e);
}
);
}
MainNotWorking : the order is not respected at all, set setdropdown1 and setdropdown2 are called sometimes before the setenum.
MainWorking:
When I have only one level of when, then the function DoOtherStuff is called before all other functions, but it's only one level. I want to do multiple chain setenum before setdropdown1 and setdropdown2 and then finally DoOtherStuff.
Use $.when().done(callback)
function MainNotWorking(ImportantModel) {
$.when(
setenum(ImportantModel)
).done(function() {
$.when(
setdropdown1(ImportantModel),
setdropdown2(ImportantModel)
).done(DoOtherStuff);
});
}
First, you should pass a function reference to then:
.then(function() { ... })
What you are passing is executed immediately, instead of when the first function is finished.
That alone would be enough, but if you wanted to "flatten" out the chaining, you could do something like this:
$.when(
setenum(ImportantModel)
).then(function() {
return $.when(
setdropdown1(ImportantModel),
setdropdown2(ImportantModel)
)
}).then(function() {
DoOtherStuff();
});
Here's a demo: http://jsfiddle.net/44e5Y/

jQuery autocomplete not filtering

I have a jQuery autocomplete control that is populating with data but the list just displays when I type anything in the box and doesn't filter my results. Does anyone know how to alter this behavior?
<script type="text/javascript">
$(function () {
$('#datePicker').datepicker();
});
$(document).ready(function() {
$("#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
url: "FacilitiesAsync",
type: 'GET',
cache: true,
data: 'sourceDb=myDb',
dataType: 'json',
success: function (json) {
response($.map(json, function (name) {
return {
label: name.label,
value: name.value
};
}));
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$("#autocomplete").text(textStatus + ', ' + errorThrown);
}
});
},
select: function (event, ui) {
$('#autocomplete').val(ui.item.label);
return false;
},
messages: {
noResults: '',
results: function () {
}
}
});
});
</script>

Categories