Jump to content

XmlHttpRequest doesn't work at the right time


bymafmaf
 Share

Recommended Posts

Hi,

 

I have this code in my start menu state.

startGame: function (pointer) {        var user = KareApi.getUser(243536);        console.log(user.name);        this.state.start('Game');    }

when user clicks to play this runs. KareApi.getUser() contains an XmlHttpRequest and returns an object from database.

getUser: function(deviceID){        var xhr = new XMLHttpRequest();        xhr.open('POST', 'http://XXX/api/user/getUser');        xhr.setRequestHeader('Content-Type', 'application/json');        xhr.onload = function() {            if (xhr.status === 200) {                var userInfo = JSON.parse(xhr.responseText);                return userInfo;            }        };                xhr.send(JSON.stringify({            deviceID: deviceID        }));    }

But it sees user variable as undefined. In debugging I see that it goes into getUser function, doesn't get in xhr.onload at first, so doesn't return anything. Then console.log runs and as expected it gives error. when I comment console.log and debug, I see that xhr.onload runs after some update functions of phaser.

 

How can I complete all requesting and returning process before console.log?

 

Or do you know a tutorial or some kind of framework that works with phaser smoothly because I'm kind of having a hard time integrating standart restful client codes..

 

Thanks in advance.

Link to comment
Share on other sites

hi again, 

lets try.  i am no fan of online editors so here is. c/p your changed code. 

 

var userinfo ; // global variable 

 

startGame: function (pointer) {
var user = KareApi.getUser(243536);
//console.log(user.name); // undefined !!!
 // show some fancy loader ! 
}

 

getUser: function(deviceID){

var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://XXX/api/user/getUser');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
// in here we set global variable 

userInfo = JSON.parse(xhr.responseText);
// stop showing some fancy screen or just state change

this.state.start('Game');
}
};

xhr.send(JSON.stringify({
deviceID: deviceID
}));
}

Link to comment
Share on other sites

It's going to have to be asynchronous. Your code that looks like this:

var user = KareApi.getUser(243536);

Won't work because KareApi.getUser is async; the function returns undefined and then, at some later time, completes and has a user object.

 

You should use the Phaser state system to help you. In your preload state, make the call to get the user as well... but instead of trying to return it (you can't), set it as a global variable on window. Then, in the update method of your preload state don't transition to the next state until that user object is populated.

function update() {  if (window.user) {    this.state.start('Game');  }}

Alternately, you could use Promises but they might not be available depending on what you're trying to support on mobile.

Link to comment
Share on other sites

@bymafmaf, it depends on your game. as i said before, i am no expert phaser but @drhayes pointed a direction using update.

imho, update creates a cpu time ( i am not sure!) but you can encapsulate your API. if update is second based, i would try update.

 

if update creates a cpu time +  if i were you, i would try this, i would like to save cpu and break rules :)

 

corrected code:
 
startGame: function (pointer) {
 // show some fancy loader ! 
var user = KareApi.getUser(243536);


}
Link to comment
Share on other sites

Sorry for late answer.

 

I moved KareApi.getUser to Boot state that is before StartMenu state which is @drhayes mentioned. So, it seems that to make it work under startmenu state so that login boxes can appear, I need one more state after startmenu. Some kind of "processing" state.

 

I'll inform when I implement it. Now I'm trying to implement Socket.IO so that it wouldbe realtime-multiplayer game.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...