Reputation: 97
trying to get the getFromWho function to return the recipient text from xml file, I can get it to log the text, but for some reason I cannot get it to return in the function.
function preSubmit(){
var optionTexts = [];
$("section").each(function(){
var h2 = $(this).find("h2").text();
optionTexts.push(h2);
optionTexts.push("\n");
$("ol li", this).each(function() { optionTexts.push($(this).text()) })
});
var splitText = optionTexts.join("\n");
console.log(splitText)
splitText += getFromWho();
return splitText;
}
function getFromWho() {
$.ajax({
type: "GET",
url: "forWho.xml",
dataType: "xml",
success: function(xml) {
console.log($(xml).find('recipient').text())
return $(xml).find('recipient').text();
}
});
}
Upvotes: 0
Views: 73
Reputation: 388316
Since your are using ajax the execution will be asynchronous, means you can't return any value from the ajax callback.
The correct way to solve this is to use a callback method or use the ajax promise.
Ex
function preSubmit(callback){
var optionTexts = [];
$("section").each(function(){
var h2 = $(this).find("h2").text();
//optionTexts.push("<b>");
optionTexts.push(h2);
optionTexts.push("\n");
$("ol li", this).each(function() { optionTexts.push($(this).text()) })
});
var splitText = optionTexts.join("\n");
getFromWho().done(function(xml){
splitText += $(xml).find('recipient').text();
callback(splitText)
});
}
function getFromWho() {
return $.ajax({
type: "GET",
url: "forWho.xml",
dataType: "xml"
});
}
Then
preSubmit(function(splitText){
//Do actions which depends on splitText
});
//You cannot do anything which depends on splitText here as preSubmit is asynchronous
Upvotes: 1