I have the following JavaScript code:
function LoadWord(currentLanguage, currentId, isBadWord)
{
var filePath, badFilePath;
switch(currentLanguage) {
case 'spanish':
filePath = 'data/spanish.xml';
badFilePath = 'data/badSpanish.xml';
break;
case 'catalan':
filePath = 'data/catalan.xml';
badFilePath = 'data/badCatalan.xml';
break;
default: return;
}
$.ajax({
type: "GET",
url: filePath,
dataType: "xml",
success: function(xml) {
$(xml).find('word').each(function(){
if($(this).find('id').text() == $.myNameSpace.cImgId)
{
$.myNameSpace.currentWord = $(this).attr('name');
$.ajax({
type: "GET",
url: badFilePath,
dataType: "xml",
success: function(xml) {
$(xml).find('word').each(function(){
for(index = 0; index < 3; index++)
{
if($(this).find('id').text() == $.myNameSpace.badWordsIds[index])
{
$.myNameSpace.badWords[index] = $(this).attr('name');
}
}
UpdateWords();
});
},
error: function(x) { alert(x.responceText); }
});
}
});
},
error: function(x) { alert(x.responceText); }
});
}
function UpdateWords()
{
var languageWordPos = randomFromTo(1, 4);
var index = 1;
var badWordsIndex = 0;
while (index < 5) {
if (index == languageWordPos ) {
SetTextToButton(index, $.myNameSpace.currentWord);
}
else {
SetTextToButton(index, $.myNameSpace.badWords[badWordsIndex]);
badWordsIndex++;
}
index++;
}
LoadUserOwnWord($.myNameSpace.lang, $.myNameSpace.cImgId);
}
function SetTextToButton(index, text)
{
console.log("SetTextToButton");
switch(index)
{
case 1:
$('#Word1').html(text);
break;
case 2:
$('#Word2').html(text);
break;
case 3:
$('#Word3').html(text);
break;
case 4:
$('#Word4').html(text);
break;
default: return;
}
}
I declare $.myNameSpace.badWords
in this line:
$.myNameSpace.badWords[index] = $(this).attr('name');
This line is declared inside second ajax call sucess function.
When I try to get a value from $.myNameSpace.badWords
here:
SetTextToButton(index, $.myNameSpace.badWords[badWordsIndex]);
I get an undeclared variable. This line is inside UpdateWords()
function.
I'm debugging with FireBug and I can't see BadWords
on $.myNameSpace
variable.
How can I fix this problem?
The correct answer is that I can't use an Array it is not initialized.
I can do this inside success function:
$.myNameSpace.badWords = new Array(3);
And it will be available to any other function.