I’m developing a Javascript game and I’m currently trying to get it to load a randomly chosen image from my database before the game is fully initiated.
I’m using an ajax call which uses a php script that selects a random image address from a table in my database and then echos this image address back to the Javascript.
I want to place this image address into the space after img.src =
To do this I’m trying to turn the ajax response into a variable that I can then place after img.src =
, so that every time the game is reloaded, a new ajax call will be made, and a randomly chosen image link will be placed after img.src =
(the img.src =
is then used by the game).
Here is the code I’m trying along with comments:
//declaring a variable called “ajaxResponse” – this is what the ajax response will be attached to:
var ajaxResponse;
//a function containing the ajax call which returns the image address as its response:
function getRandomPicture() {
$.ajax({
url: 'picturerandomizer.php',
data: "",
dataType: 'json',
success: function(response){
//attaching the response to the variable created at the start:
ajaxResponse = response;
}});
};
//this is where game code is, including the definition of ``img.src``, which I’m trying to define here as the ajaxResponse variable.
img.src = ajaxResponse;
This isn't currently loading an image into the game (the game initiates but there's a blank space where the image should be located). I think I'm doing things in the wrong order? I think I need to initiate the ajax call, and then place the game's code inside the ajax call's success function. That way a random image will always be defined before the game gets loaded, but I'm not sure exactly how to do that.
If the ajax call happens to fail then I'd still like to initiate the game but with a statically defined img src
instead, for example:
img.src = 'image001.jpg';
I'd really appreciate anyone's advice on the correct way to implement this code. Thanks so much in advance!