Jump to content

Load SQL database in Phaser


Recommended Posts

Hi everyone.

I'm trying to learn something about how to load database information in my phaser games. Currently, I want to load some questions for a quizz game from a SQL database.

I've searched online and I found a method that works but I don't know if it's the best option. 

Making a XMLHttpRequest I can load a PHP file in which I load the db info and then parse it into a JSON. As I said, it works, but then I don't know how to send the results back to the game, since is an asynchronous proccess.

Let me explain myself with the code:

Quizz.Game.prototype = {
	create: function(){
	getQuestion: function(){
		var request = new XMLHttpRequest();
		request.open('POST', 'getQuestion.php', true);
		request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		request.onload = function(){
			if(request.status >= 200 && request.status < 400){
				var result = JSON.parse(request.responseText);
    sendQuestion: function(){
        //The next code

In this example I tried to load the question and then print it on screen or something, but I get the error 'this.sendQuestion()' is not a function, seems like the context is no longer 'this'... 

I guess my question is if you have some procedure you usually use for do this, or if there's a better way of doing it.

Thank you for sharing!


Link to comment
Share on other sites

If i had to do something similar instead of writing the whole code myself I would try to use some library for ajax request. You just call something like $.ajax with parameters you want and to get response. 

Jquery might be the most popular for such kind of things but it is quite big there should be smaller libraries that could do the same.


Link to comment
Share on other sites

Off the top of my head axios, fetch (polyfill), reqwest, request and superagent would all handle ajax for you, although using XMLHttpRequest as you have is pretty straight-forward (you might want to check out the fetch api though, which is native in all modern browsers and supersedes XHR), although, your issue is a scope issue rather than an ajax issue.

Try to avoid `var self = this` or `var that = this`, its error-prone and makes refactoring almost impossible. Consider using .bind instead (or .apply or .call) to manage scope.

On a side note, check out some docs about REST. You're making a POST request to get some data, you should use a GET, a POST is for sending data to a service and requesting that it gets stored as a new resource, or sometimes amending or overriding an existing resource (PUT, or even PATCH, should really be used in this case). As its your service it doesn't really matter, but its worth learning and adhering to certain conventions.

Link to comment
Share on other sites


  • Recently Browsing   0 members

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