Поскольку ваш AJAX-запрос асинхронный , поэтому код, следующий за ним , не ожидает ответа до его выполнения.
Любой код, который полагается науспешный ответ должен быть помещен в или вызван из обратного вызова success:
.
function getImage(){
img = new Object(); // 1. create object
// 2. send request
$.ajax({
type: "GET",
url: "hvimage.xml",
dataType: "xml",
success: function(xmlData){
// 4. response is received, and callback runs
var randImageId = Math.floor(Math.random()*3);
$(xmlData).find("image").each(function(index, e){
if(index == randImageId){
img.id = $(this).attr("id");
img.location = $(this).find("location").text();
img.answer = $(this).find("answer").text();
}
});
},
error: function(xmdData){
alert("error");
}
});
// 3. fire alerts
alert("test");
alert(img.location); //Keep getting undefined here..
}