The problem is that while this section of your code is waiting for the ajax response:
> $.get('ajax.txt', function(data) { > splitted = data.split(','); > }); This section is already running... > var slide = $(elm).attr('slide'); > var total = splitted.length; > var next = slide+1 > var picture = splitted[next]; .... Something like this should work: $(document).ready(function(){ $.get('ajax.txt',function(received) { if(received.indexOf(',') >= 0) { var images = received.split(','); var total = images.length; console.debug('Length: '+total); /* var slide = $(elm).attr('slide'); // without markup, we'll just assume this value = 1 */ var slide = 1; console.log('Slide: '+slide); var next = parseInt(slide)+1; console.log('Next: '+next); if(images[next] !== 'undefined') { var picture = images[next]; console.log('Picture: '+picture); runAnimation(elm,next,picture) } } } function runAnimation(elm,next,picture) { $(elm).fadeOut(1000, function() { $(elm).attr('slide', next).css('background', 'url('+path+picture +')'); $(elm).fadeIn (1000); }); } });