needing to get a http get request to get a code from the json

MaxPKjj

Villager
Member
Joined
May 5, 2022
Messages
9
Reaction score
3
First Language
English
Primarily Uses
RMMZ
I need to be able to save a code from a http get request to a game variable as I want the code to change every so often.

im not sure how to go about even doing that if need be an example json output from the site hosting the code:
Code:
b'{"items":[{"_id":"SINGLE_ITEM_ID","_owner":"c4e0080b-3101-43d8-9144-8cd374e5b21b","_createdDate":"2022-05-24T23:34:02.328Z","_updatedDate":"2022-05-26T00:36:24.498Z","code":1234567}]}'

i need it to get only the code 1234567 from the json output to a game variable. any help would be greatly appriciated.
 

Andar

Veteran
Veteran
Joined
Mar 5, 2013
Messages
38,001
Reaction score
10,556
First Language
German
Primarily Uses
RMMV
your post is a bit confusing, can you explain more?

for example why don't you just load the json like the engine is loading all json data?
 

MaxPKjj

Villager
Member
Joined
May 5, 2022
Messages
9
Reaction score
3
First Language
English
Primarily Uses
RMMZ
your post is a bit confusing, can you explain more?

for example why don't you just load the json like the engine is loading all json data?
My problem is that i dont know how the game uses json and i need the data pulled from my website as it is a dev code that i wanted changed every so often. When i say dev code i mean it is literally a code to unlock everything. I dont get how to get the data into the game with http get. My website provides the data in json format.

The game will not be being hosted on a website but it is rather going to be packadged up as a mobile app when its done.
 

Arthran

Veteran
Veteran
Joined
Jun 25, 2021
Messages
873
Reaction score
1,080
First Language
English
Primarily Uses
RMMZ
Are you saying that you need help performing the get request? Or are you saying that you already know how to do that, but you don't know how to handle the JSON string?
 

MaxPKjj

Villager
Member
Joined
May 5, 2022
Messages
9
Reaction score
3
First Language
English
Primarily Uses
RMMZ
Are you saying that you need help performing the get request? Or are you saying that you already know how to do that, but you don't know how to handle the JSON string?
Unfortunately both as im trying to learn how to code javascript. The website hosts the http get just fine. And i can pull it with python i just dont know how to get it or handle it in javascript. I do need to save that as a variable in game.
 

Arthran

Veteran
Veteran
Joined
Jun 25, 2021
Messages
873
Reaction score
1,080
First Language
English
Primarily Uses
RMMZ
The best way to go about it really depends on exactly what you're trying to do. For example, how do we need to handle error situations (such as if the server can't be reached, or if the string gets returned incorrectly, or something like that)? And do we need to pause all other execution while waiting for the request to complete, or can it be asynchronous?

But here is a basic example of how this could be done:

JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://butts.butt/moarbutts", false);
xhttp.send();

if (xhttp.status === 200) {  // This means that the request was successful
    let butt = JSON.parse(xhttp.responseText);
    $gameVariables.setValue(1337, butt.items[0].code);
} else {  // Request unsuccessful
    $gameVariables.setValue(1337, 9999999);
}

Assumptions I made in that code:
  • The b that you have at the front of your string is some type of error on your part, and that it won't actually be included in the response
  • The game variable that you want to save the result to has an ID of 1337
  • The URL that you're making the request to is https://butts.butt/moarbutts
  • If the request to the server is unsuccessful, you want to set the value of your game variable to 9999999
  • You want to send the request synchronously (i.e. the code will wait for the request to complete before it resumes execution)
  • The response that your server sends will always be in the correct format.
You'll obviously need to change the occurrences of 1337 to the actual ID of the variable that you want to use, and you'll want to change the https://butts.butt/moarbutts to match your actual URL.
 
Last edited:

MaxPKjj

Villager
Member
Joined
May 5, 2022
Messages
9
Reaction score
3
First Language
English
Primarily Uses
RMMZ
The best way to go about it really depends on exactly what you're trying to do. For example, how do we need to handle error situations (such as if the server can't be reached, or if the string gets returned incorrectly, or something like that)? And do we need to pause all other execution while waiting for the request to complete, or can it be asynchronous?

But here is a basic example of how this could be done:

JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://butts.butt/moarbutts", false);
xhttp.send();

if (xhttp.status === 200) {  // This means that the request was successful
    let butt = JSON.parse(xhttp.responseText);
    $gameVariables.setValue(1337, butt.items[0].code);
}else {  // Request unsuccessful
    $gameVariables.setValue(1337, 9999999);
}

Assumptions I made in that code:
  • The b that you have at the front of your string is some type of error on your part, and that it won't actually be included in the response
  • The game variable that you want to save the result to has an ID of 1337
  • The URL that you're making the request to is https://butts.butt/moarbutts
  • If the request to the server is unsuccessful, you want to set the value of your game variable to 9999999
  • You want to send the request synchronously (i.e. the code will wait for the request to complete before it resumes execution)
  • The response that your server sends will always be in the correct format.
You'll obviously need to change the occurrences of 1337 to the actual ID of the variable that you want to use, and you'll want to change the https://butts.butt/moarbutts to match your actual URL.
That worked perfectly thank you so much.
 

MaxPKjj

Villager
Member
Joined
May 5, 2022
Messages
9
Reaction score
3
First Language
English
Primarily Uses
RMMZ
The best way to go about it really depends on exactly what you're trying to do. For example, how do we need to handle error situations (such as if the server can't be reached, or if the string gets returned incorrectly, or something like that)? And do we need to pause all other execution while waiting for the request to complete, or can it be asynchronous?

But here is a basic example of how this could be done:

JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://butts.butt/moarbutts", false);
xhttp.send();

if (xhttp.status === 200) {  // This means that the request was successful
    let butt = JSON.parse(xhttp.responseText);
    $gameVariables.setValue(1337, butt.items[0].code);
}else {  // Request unsuccessful
    $gameVariables.setValue(1337, 9999999);
}

Assumptions I made in that code:
  • The b that you have at the front of your string is some type of error on your part, and that it won't actually be included in the response
  • The game variable that you want to save the result to has an ID of 1337
  • The URL that you're making the request to is https://butts.butt/moarbutts
  • If the request to the server is unsuccessful, you want to set the value of your game variable to 9999999
  • You want to send the request synchronously (i.e. the code will wait for the request to complete before it resumes execution)
  • The response that your server sends will always be in the correct format.
You'll obviously need to change the occurrences of 1337 to the actual ID of the variable that you want to use, and you'll want to change the https://butts.butt/moarbutts to match your actual URL.


 

Arthran

Veteran
Veteran
Joined
Jun 25, 2021
Messages
873
Reaction score
1,080
First Language
English
Primarily Uses
RMMZ
@MaxPKjj

Looks pretty cool. If you wanted to be a little more fancy, you could turn it into an asynchronous request instead, and then display a loading spinner (or something along those lines) until the request is complete. That way, the player won't be confused by the game freezing while the request is happening.

It'd be a little more work, but not terribly difficult.
 

Arthran

Veteran
Veteran
Joined
Jun 25, 2021
Messages
873
Reaction score
1,080
First Language
English
Primarily Uses
RMMZ
@MaxPKjj

My curiosity got the better of me, so I went ahead and wrote the code to implement what I mentioned before (an asynchronous request with a loading spinner). I'd recommend that you try this out instead. It won't lock up the game while the request is happening, so it looks a littler nicer. Also, in my testing, it seems to complete the request quicker--In my testing, the spinner never even needed to show up, because the request completed instantly every time.

It does require two parts though. You need to do a script call, and then you also need to make a loop right below the script call. Here is the script call:
JavaScript:
$gameVariables.setValue(36, 0); // Must initialize the variable to 0 each time

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://butts.butt/moarbutts?howmany=allthebutts", true);
xhttp.timeout = 5000;

xhttp.onload = function () {
    if (xhttp.readyState === 4) {
        if (xhttp.status === 200) {  // Request was successful
            let butt = JSON.parse(xhttp.responseText);
            $gameVariables.setValue(36, butt.items[0].code);
        }else {  // Request unsuccessful
            $gameVariables.setValue(36, 9999999);
        }
        Graphics.endLoading();
    }
};

xhttp.ontimeout = function () {
    $gameVariables.setValue(36, 9999999);
    Graphics.endLoading();
};

xhttp.onerror = function () {
    $gameVariables.setValue(36, 9999999);
    Graphics.endLoading();
};

Graphics.startLoading();
xhttp.send();
Please note that the last argument in the xhttp.open function is now true instead of false.

Immediately after that script call, you will need to put this loop in your event:
Code:
◆Loop
  ◆If:Secret Code ≠ 0
    ◆Break Loop
    ◆
  :End
  ◆
:Repeat Above
It's just an empty loop that keeps executing until your variable #36 no longer equals 0. The purpose of it is to keep the event from continuing past that point until the http request has completed.

*edit* Beefed up the script a little to account for more failure conditions.
 
Last edited:

MaxPKjj

Villager
Member
Joined
May 5, 2022
Messages
9
Reaction score
3
First Language
English
Primarily Uses
RMMZ
@MaxPKjj

My curiosity got the better of me, so I went ahead and wrote the code to implement what I mentioned before (an asynchronous request with a loading spinner). I'd recommend that you try this out instead. It won't lock up the game while the request is happening, so it looks a littler nicer. Also, in my testing, it seems to complete the request quicker--In my testing, the spinner never even needed to show up, because the request completed instantly every time.

It does require two parts though. You need to do a script call, and then you also need to make a loop right below the script call. Here is the script call:
JavaScript:
$gameVariables.setValue(36, 0); // Must initialize the variable to 0 each time

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://butts.butt/moarbutts?howmany=allthebutts", true);
xhttp.timeout = 5000;

xhttp.onload = function () {
    if (xhttp.readyState === 4) {
        if (xhttp.status === 200) {  // Request was successful
            let butt = JSON.parse(xhttp.responseText);
            $gameVariables.setValue(36, butt.items[0].code);
        }else {  // Request unsuccessful
            $gameVariables.setValue(36, 9999999);
        }
        Graphics.endLoading();
    }
};

xhttp.ontimeout = function () {
    $gameVariables.setValue(36, 9999999);
    Graphics.endLoading();
};

xhttp.onerror = function () {
    $gameVariables.setValue(36, 9999999);
    Graphics.endLoading();
};

Graphics.startLoading();
xhttp.send();
Please note that the last argument in the xhttp.open function is now true instead of false.

Immediately after that script call, you will need to put this loop in your event:
Code:
◆Loop
  ◆If:Secret Code ≠ 0
    ◆Break Loop
    ◆
  :End
  ◆
:Repeat Above
It's just an empty loop that keeps executing until your variable #36 no longer equals 0. The purpose of it is to keep the event from continuing past that point until the http request has completed.

*edit* Beefed up the script a little to account for more failure conditions.
That looks awesome and runs well. During testing for some reason deploying it as android and installing a built apk on the phone bugs this code. i tried with the other one and same thing and deploying to itch.io does the same thing but deploying to windows works. Yet upon closer inspection the http get is being replied to just fine from the hosting website and the reply is correct. So i believe there is something stopping the game from being able to receive the get request from the deployed version.

 
Last edited:

Arthran

Veteran
Veteran
Joined
Jun 25, 2021
Messages
873
Reaction score
1,080
First Language
English
Primarily Uses
RMMZ
In what way is it bugging out? Is it just coming up with 9999999 every time? Or is it actually crashing or something? Any chance you can get an error message? On your itch deployment, you can press F12 to open up the developer console, and then once you try to open the door, it should show you some type of error message.

But I would guess that it's a security thing. IIRC, some browsers don't allow a web application to make XMLHttpRequests to a different domain. I'd imagine that there are ways to get around this, but I'm not a web programmer, so I don't know them off the top of my head. Unfortunately, I'm going to be swamped for the next several days, and don't really have time to read up on it. If you don't manage to come up with a solution by the the middle of next week, I can try to figure it out.
 

MaxPKjj

Villager
Member
Joined
May 5, 2022
Messages
9
Reaction score
3
First Language
English
Primarily Uses
RMMZ
In what way is it bugging out? Is it just coming up with 9999999 every time? Or is it actually crashing or something? Any chance you can get an error message? On your itch deployment, you can press F12 to open up the developer console, and then once you try to open the door, it should show you some type of error message.

But I would guess that it's a security thing. IIRC, some browsers don't allow a web application to make XMLHttpRequests to a different domain. I'd imagine that there are ways to get around this, but I'm not a web programmer, so I don't know them off the top of my head. Unfortunately, I'm going to be swamped for the next several days, and don't really have time to read up on it. If you don't manage to come up with a solution by the the middle of next week, I can try to figure it out.
Code:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://serverurl. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

Fix found i needed the cors headers in http get response on the website housing the code so when its all said and done.


Before:
JavaScript:
export function get_devcode(code) {
  let options = {
    "headers": {
      "Content-Type": "application/json",
    }
  };
  return wixData.query("TheMazeCode")
    .find()
    .then(results => {
      if (results.items.length > 0) {
        options.body ={
          "items": results.items
        }
        return ok(options);
      }
    })
}

After:
JavaScript:
export function get_devcode(code) {
  let options = {
    "headers": {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
      "Access-Control-Max-Age": "86400"
    }
  };
  return wixData.query("TheMazeCode")
    .find()
    .then(results => {
      if (results.items.length > 0) {
        options.body ={
          "items": results.items
        }
        return ok(options);
      }
    })
}
 
Last edited:

Latest Threads

Latest Posts

Latest Profile Posts

Best explanation of "Confirmation Bias": "If you go looking for a fight, you will always find one". If you always look for something, you'll find it. Negativity or Positivity. This is just a reminder to spend time looking for some Positivity today. :D Ya'll have earned it and deserve it.
And now all my attacking skills suddenly heal instead of doing damage...Even kills and revives. Because ofc they do xD
Spend more time building up what you like, and stop tearing down things you don't. If you only tear stuff down, nobody will get to enjoy anything.
Work, work. Streaming in 20 minutes or so.
Finnuval wrote on fizzly's profile.
Cool.looking avatar ;)

Forum statistics

Threads
129,931
Messages
1,206,337
Members
171,130
Latest member
thepipa666
Top