I have a question regarding ajax array. I have create two arrays in a javascript file like below.
$(document).ready(function () {
categoryarray = [];
productarray = [];
Then if I want to refer to these arrays from another javascript file with the script inside html follows the script of the javascript file that creates two arrays, but it doesn't show anything, not even console reporting error. Below is how I refered the array in another javascript file, it didn't work.
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'my_script.js',
success: function(data) {
for(var k=0;k<categoryarray.length;k++){
if(categoryarray[k][0]!==""){
$('.tree').append('<li id="Cate_' + k + '">'+categoryarray[k][1]+'</li>');
for(var l=0;l<productarray.length;l++){
if(categoryarray[k][0]==productarray[l][2]){
$('#Cate_' + k).append('<ul id="Pro_' + l + '"></ul>');
$('#Pro_' + l).append("<li>"+productarray[l][1]+"</li>");
}
}
}
}
},
error: function() {
$('.tree').text('Failed to load the data');
console.log('Error');
}
});
});
Can anyone tell me what I have done wrong and how to fix them? Many thanks!!!
First of all place your code inside a function that you will call on some event. If you want to process your arrays after AJAX call then call that function after AJAX success. Browser render HTML from top to bottom so your script in HTML will run as soon as browser bump into script. On the other hand jQuery on ready will wait until all of the page content is fully loaded (all images, assets etc) - whole DOM, so your arrays will stay undefined. You can fix it either by moving that code from HTML to jQuery ready function or by moving array declarations in HTML. Anyway, if that script from HTML should run when document is ready, then it is more reasonable to move javascript code from HTML to jQuery ready function.