0

I making a loader of .obj models for WebGL on javascript, and the problblem i'm having appears to be something with the XMLHttpRequest method, let me explain;

var textureArray=[];
loadTexture=function(name){
    var request = new XMLHttpRequest();
    request.open("GET", name+'.mtl');
    request.onreadystatechange = function () {
        if (request.readyState == 4) {
            //do the stuff to put the textures in textureArray
        }
    }
    request.send();
}

And let's say the method that uses it is this:

loadObjModel=function(name){
      loadTexture(name);
    //Check if the texture loaded
}

The thing is, when i say "Check if the texture loaded", the variable "textureArray" it's empty, but if i check immediately after i "do the stuff to put the texture in textureArray" (inside the onreadystatechange function) it does show the textures loaded correctly. I found what the problem is, it takes time to read the file and loop through the lines, so at the moment i "Check if the texture loaded" it hasn't finished, but when i do it at the end of "do the stuff to put the texture in textureArray" sows it loaded correctly because it had to wait to load everything and then show what the textureArray had.

The big problem here is that, when i try to use the textures i loaded at "Check if the texture loaded", i can't...because they aren't there, and i have seen webGL loaders douing it in this exact way and not having that problem. Wat could i be douing wrong?, thanks for the thoughts :)

Orion390
  • 127
  • 1
  • 8

1 Answers1

-1

You can make your ajax call synchronous by adding a false when you call the open method:

request.open("GET", name+'.mtl', false);

This should make your script wait until loadTexture() returns before doing the 'Check if the texture loaded' stuff.

MattT
  • 134
  • 6
  • This is exactly what i needed, extreme thanks MattT! :D – Orion390 Jun 27 '14 at 17:03
  • using synchronous XHR requests [is](http://updates.html5rocks.com/2012/01/Getting-Rid-of-Synchronous-XHRs) [considered](http://blogs.msdn.com/b/wer/archive/2011/08/03/why-you-should-use-xmlhttprequest-asynchronously.aspx) [very](http://programmers.stackexchange.com/questions/112551/should-we-still-consider-a-synced-xmlhttprequest-bad-practice) [bad](http://stackoverflow.com/questions/6517403/what-are-the-drawbacks-of-using-synchronous-ajax-call) [practice](http://ajaxblog.com/archives/2005/05/25/synchronous-requests-bad). – gman Jun 27 '14 at 18:10