2

I have a function that returns the highest value of an attribute in an xml file

The Value returned is always 0, so I think the value under the JQuery function doesnt know what happens inside of it. Here is the function:

function findHighestValue(url,attr){
var highestValue = 0;
$.ajax({
    type: "GET",
    url: url,
    dataType: "xml",
    success: function(xml) {
        $(xml).find("achievement").each(function(){
             var value = $(this).find(attr).text();
             value = value*1;//typecast
             console.log("value: "+value);//shows correct value
             console.log("highestValue in ajax: "+highestValue);//shows correct value
             if (value >= highestValue){
                 highestValue = value;
                 console.log("Value higher highesValue detected!");//works as intended
             }

        });
    }
});
console.log("Highest Value: "+highestValue);// is 0 again
return highestValue;//always returns 0
}

2 Answers 2

6

As it's an ajax request the last two lines are hit before the lines inside the success method.

You cannot return a value from an ajax request unless you set async: false

You need to process the value via the success callback rather than trying to return it.

Sign up to request clarification or add additional context in comments.

2 Comments

I learned my lesson, it makes totally sense. I set the async to false and now it works as intendted. Thank you!
@dan I don't advise setting async to false though as this will freeze the browser if your ajax request takes a long time. Much better to use the callback function to perform your logic.
2

AJAX is asynchronous, thus it doesn't wait for your $.ajax() call before calling console.log(), hence the wrong value. So you are right in the sense that doesnt know what happens inside of it

To tackle this, you can either place the rest of your function's logic inside success property of your $.ajax call or set async: false, be warned though that your browser will "freeze" a bit when $.ajax() happens

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.