anawak82 wrote:
function getPrice(id)
{
$.get('db.xml', function(d){
$(d).find('data').each(function(){
var $data = $(this);
if ($data.find("id").text() == id)
{
var price = $data.find("preis").text().trim();
return price;
}
});
});
};
I assume that the nested functions are part of the problem, but I
don't know how to solve it.
Your return statement is returning out of the function inside the
"each". That is not getting back to the outer function. In this case,
returning false works like a "break" statement in a loop, returning true
works like a "continue" statement, and either way, it's not what you
want. And although something like this looks better, it will also not work:
function getPrice(id) {
var price;
$.get('db.xml', function(d) {
$(d).find('data').each(function() {
var $data = $(this);
if ($data.find("id").text() == id) {
price = $data.find("preis").text().trim();
return false; // ends the each loop immediately.
}
});
});
return price;
};
That's because the AJAX call returns immediately, and there is no wait
for price to be updated. Essentially, you need to structure your code
so that any result of an AJAX call is handled with a callback. Let's
say you have some function
function handlePriceUpdate(id, price) {
// ...
}
Then you could invoke it from your function like this:
function updatePrice(id) {
$.get('db.xml', function(d) {
$(d).find('data').each(function() {
var $data = $(this);
if ($data.find("id").text() == id) {
var price = $data.find("preis").text().trim();
handlePriceUpdate(id, price);
return false; // ends the each loop immediately.
}
});
});
};
And perhaps even better would be to pass the function directly into the
call, like this:
function updatePrice(id, handler) {
$.get('db.xml', function(d) {
$(d).find('data').each(function() {
var $data = $(this);
if ($data.find("id").text() == id) {
var price = $data.find("preis").text().trim();
handler(price, id /* needed? */);
return false; // ends the each loop immediately.
}
});
});
};
Note that none of this is tested at all.
Cheers,
-- Scott