0

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();
        }
    });
}

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.