Javascript boolean results failing [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Why does this variable (lanFound) become undefined?
I get the following output:
Lightbulb moment! :)
As I typed the sequence of output gives it away! ajax is asynch, so the true comes back after the code has continued! I'll post anyway, might be handy for someone!
testing for: DK
result is: undefined
/sites/cspdKnowledgeAssemblyPlatform/ApprovedContent/DKCover Letter.docx succeeded
I have a set of docx files, but am adding support for languages, but to test the files (docx) have been added I use the following code (OK this is a long had variant to allow me to debug):
fileUrl = filePath + fileName;
if (lan != "EN"){
showNotification("testing for: " + lan);
var lanFound = false;
lanFound = checkURL(filePath + lan + fileName);
showNotification("result is: " + lanFound);
if(lanFound){
debugger;
fileUrl = filePath + lan + fileName;
showNotification("found " + fileUrl);
}
}
function checkURL(urlFileName){
$.get(urlFileName)
.fail(function() {
showNotification(urlFileName + " failed");
return false;
})
.done (function() {
showNotification(urlFileName + " succeeded");
return true;
});
}
You can ignore this - just added for context of "showNotification")
function showNotification(content){
var currentText = $( "#resultpanel" ).html();
currentText = currentText + "<br/>" + content;
$( "#resultpanel" ).html(currentText);
}

You cannot call an ajax call in this manner, the code will pass by before the result is returned, due to it being asynchronous, the result being the variable is read as undefined at the point at which the code passes it.
Sorry as I typed the question, I realised the answer, but posted anyway, as this might be handy for someone.

Related

Javascript custom library issue [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have looked and looked and I am still scratching my head. If I have missed something obvious, I apologise. I have tried to create a custom library of functions that I have written myself (thanks stackoverflow for helping me work that one out....). I then have a javascript file that loads when the web page is called, which in turn calls said functions in my custom library.
I have a function called getConfig() that does the obvious. It gets a JSON file with the configuration details for my server that hosts all of my RESTful web services. When I step through the code, the configuration details are returning as I would expect, however, when I load the web page at full speed, the configuration object comes back as undefined. I thought it might be a timing thing, so I wrapped everything in a $(document).ready(function()) block, but no go. I even tried a window.onload = function(){} block to make sure everything is loaded before the custom libraries are called. No luck! Its doing my head in as I cannot for the life of me work out what is going on.
My custom library file looks like this with filename xtendLibs.js
var xtendLibs = {
getConfig : function(){
var CONFIG;
$.getJSON("/js/config.json", function(json){
CONFIG = json;
});
return CONFIG;
},
getObjects : function(config, medicareno, medicarelineno, objectType){
var object;
var urlString = config.scheme + config.muleHost + config.mulePort + ":/patients/";
switch(objectType){
case ("details") :
urlString = urlString + "details/" + medicareno + "/" + medicarelineno ;
break;
case ("appointments") :
urlString = urlString + "appointments/" + medicareno +"/" + medicarelineno;
break;
}
$.ajax({
type : 'GET',
url : urlString,
success : function(data){
object = data;
},
failure : function(){
alert("Failure");
}
});
return object;
},
getUrlParameters : function(){
var paramsArray = window.location.search.substring(1).split("&");
var obj = [];
var tempArray;
var paramName,paramValue;
for(var i = 0; i < paramsArray.length; i++){
tempArray = paramsArray[i].split("=");
paramName = tempArray[0];
paramValue = tempArray[1];
obj[paramName] = paramValue;
}
return obj;
}
};
The javascript file that calls the various functions in the above file looks like this appts.js
window.onload = function(){
var config, params, appointments;
params = xtendLibs.getUrlParameters(); // This line works - and params is returned
config = xtendLibs.getConfig(); // This line fails but will work if I step through the code
appointments = xtendLibs.getObjects( config,
params["medicareno"],
params["medicarelineno"],
"appointments");
console.log(params);
}
I am truly stumped. Any help would be greatly appreciated.
Ajax is async process, so when getJson is called it does not stop the execution of next statement.
getConfig : function(){
var CONFIG;
$.getJSON("/js/config.json", function(json){
CONFIG = json;
});
return CONFIG;
}
When getJson is called it switches to a new thread, and the next statement which is in this case is "return CONFIG;" is executed. However, CONFIG has not been defined yet, so it is returning as undefined.
How Could you solve this problem?
You could not solve this problem. Not using this code design. You could non async the ajax, but it will make your page freeze.
You could set a global variable "config" when "getConfig" is called and check whether the config variable is defined when executing any function concerning it, but the best approach would be to pass a function, containing all the statements to be executed when config has finished loading, in getConfig function and call it when "/js/config.json" has loaded.

jQuery.ajax returning empty array [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
I'm currently learning to use API's. I'm retrieving data from my Github repo. I'm trying to have the script load the JSON info into the githubData variable. But when I log the githubData variable to console it returns an empty array.
Yet, if I create a new variable with the exact same function after the page is loaded the script works exactly as it should.
When the page is loading, it's not loading the actual data. It loads an an empty array. I realize the function is asynchronous, so how would I go about getting the array to not be empty when I load the page?
Here's my code:
var githubAPI = 'https://api.github.com/repos/zacharysohovich/ticTacToe/readme';
var items = {};
jQuery.ajax({
url: githubAPI,
contentType: 'application/json; charset=utf-8',
success: function(resultData) {
$.each(resultData, function(key,val) {
items[key] = val;
});
}
});
var githubData = $.map(items,function(k,v) {
return ("<p>" + k + ": " + v + "</p>");
});
The problem is that its an asynchronous call meaning that once it fires of the request it goes onto the next piece of code. Once it gets to githubData items is still an empty object because the api response hasn't been received yet.
I would instantiate the githubData variable right below var items = {}
like so
var items = {}
var githubData;
and then in the success: function after you do the $.each you can put the
githubData = $.map(items,function(k,v) {
return ("<p>" + k + ": " + v + "</p>");
});
this ensures that the api call has finished and items should have something in it as long as the response came back with something

Return data is not working within http request in angular [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have the below function that has an http request in angular. In the success part, I am trying to return the provided data, and return the value in my setTextFile() function, but it is undefined. I have checked that data is not null or undefined, so I know it contains information, but I don't understand why it's not returning that content.
var showFile = function (txtFile, host) {
var datData;
var url = 'rest/archive-viewer/spanish-discount/' +
$rootScope.currentEnv + '/' +
host + '/' +
txtFile;
$http.get(url).success(function (data) {
$scope.sendingMessage = "Getting file";
$scope.sending = false;
$scope.sendingMessage = "";
return data;
}).error(function (data) {
$scope.sendingMessage = "Creation failed";
$scope.sending = false;
});
}
$scope.pullFiles();
};
Here is my setTextFile function who's return value is undefined as a result of the showFile() return value.
var setTextFile = function (file,host) {
console.log("Is this null " + showFile(file, host));
return showFile(file, host);
}
That http request is asynchronous. What I would suggest you to do is assigning data to a scope veriable something like : $scope.setTextFile = data in the success function you have passed in ajax request. Instead you can make a function to set the data and trigger the function inside success function.

Ajax Request wont work unless I use alert() [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I've been trying for hours to get this to work, but it's just not budging; I have the following code:
var text = "";
function getText(c1, c2)
{
url = "http://en.wikipedia.org/w/api.php?format=json&action=query&titles=" + c1 + "-" + c2 + "_relations&prop=revisions&rvprop=content"
$.ajax({
type: "GET",
dataType: "jsonp",
async: false,
url: url,
success: function (data) {
var obj = (data.query.pages );
var keys = [];
for(var k in obj) keys.push(k);
if (keys[0] == -1) {
//Link doesnt exist
text = "-1";
return text;
}
//Link Exists
else {
link = "http://en.wikipedia.org/wiki/" + c1 + "-" + c2 + "_relations"
text = c1 + "-" + c2 + " Relations"
return text;
}
}
});
return text;
}
var a = (getText(country1, country2))
alert(text);
alert(a);
I'm making an ajax request; a simple inquiry to see if wiki has a page between any 2 given countrie.
If I use alert inside, it works fine, and it returns the correct data inside the text variable. However, when the getText function is called outside, the text variable is always empty. I've tried everything I can think of, including getting the app to sleep for some time, but even that didn't work. I know the async doesn't work from ajax 1.8 onwards, but is there anyway around this?
Thanks in advance.
It is because the asynchronous behavior of ajax. You can't return values from ajax like this way. Because the function will not wait for the success event to happen.
When you put an alert inside that function, success event may occur before the user clicks on alert. That is why it returning value. Otherwise it will not return the value.
Its not a good practice to use async : false in ajax calls. It will freeze the browser.
Good practice is to call a method from the ajax success with the returned data, then do operations with that data inside the function.

Javascript variable not updating value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
This is makinkg me crazy, i cant Get the outside variable Get the inside data
Sorry for the bad formating I'm writing from the phone, if someone can helpme out with the format I appreciate it
window.getReasons = function(line) {
var $reasons;
$reasons = "";
$.get(window.location.protocol + "//" + window.location.host + "/" + "allLineReasons.js?line=" + line, function(returnData) {
$reasons = returnData.toString();
return console.log("T_T ----->" + returnData.toString());
}, "html");
console.log($reasons);
return $reasons;
};
The most important thing for you to understand is that $.get() is ASYNCHRONOUS by default. So what is happening is that your console.log() and return statements that follow your call to get() are executing before the get() has returned it's value.
You might look to utilize the when() method here to handle the deferred object that is returned from get()
window.getReasons = function(line) {
var reasons = '';
$.when(
$.get(window.location.protocol + "//" + window.location.host + "/" + "allLineReasons.js?line=" + line)
).done(function(jqxhr) {
data = jqxhr[0];
reasons = data.toString();
});
console.log(reasons);
return reasons;
}
$reasons won't be updated until after the GET completes on the server and the response is returned. But your console.log will execute immediately after the request is made.

Categories

Resources