0

I'm working on a small text game in js, and the easiest way I found to have save text is to use text files. I can order them in different folders, they really light and they're easily identifiable and editable in case I need to make changes.

I'm loading them using ajax

    $.ajax({
    url: 'text/example.txt',
    success: function(text){
            document.getElementById("main").innerHTML = document.getElementById("main").innerHTML + text;
    }
});

As it was suggested to me in another thread.

And honestly, so far it's been working pretty well, in single-cases scenarios. When only one TXT file needs to be displayed there are literally no problems. But, unfortunately in cases where a lot of different files need to be displayed in a correct order (let's say around 10 different files), the text gets messed up and loads out of order. I'm going to suppose this is because it just can't fetch the txt file fast enough.

So at this point I'm really not too sure what to do.

Is there a way to get my script to wait before printing the next piece of text before displaying one that still hasn't loaded?

Maybe a way to load all the txt files when the site is accessed?

My knowledge is pretty limited so I'm really not sure how this could be fixed.

Tried searching google and stackoverflow, none of the threads I found are helping me, perhaps because I'm really not an expert.

Eight
  • 29
  • 6

1 Answers1

1

You can achieve with callback, the following way will call ajax one by one after they finish:

//setup an array of AJAX url
var ajaxes  = [{ url : 'text/example.txt'}, { url : 'text/example1.txt'}],
    current = 0;

//declare your function to run AJAX requests
function do_ajax() {

    //check to make sure there are more requests to make
    if (current < ajaxes.length) {

        //make the AJAX request with the given data from the `ajaxes` array of objects
        $.ajax({
            url      : ajaxes[current].url,
            success  : function (text) {
                document.getElementById("main").innerHTML = document.getElementById("main").innerHTML + text;
                //increment the `current` counter and recursively call this function again
                current++;
                do_ajax();
            }
        });
    }
}

//run the AJAX function for the first time when you want
do_ajax();
Manwal
  • 23,450
  • 12
  • 63
  • 93
  • I can't create an array with all my text files, I have something like 150 of them already. – Eight Jan 08 '16 at 10:12