GMS 2 Json Decode Error

F

FuRyvok

Guest
Hello, i have a button, when i click on it it sends out a HTTP request

Code:
//This is on the left pressed event
http_get("http://mywebsite.com/generate.php");
It should generate a json with random values what looks like:

Code:
{"s1o1":"6","s2o1":"5"}
Code:
//This is in the Button's Async - HTTP Event

if(async_load[? "status"]<0){
    show_message("Cannot connect to server.");
}else{
    var json       = async_load[? "result"];
    var map        = json_decode(json);
}
This code works fine, but sometimes the game crashing and it says the JSON is undefined.
 

2Dcube

Member
it could be that your game is receiving some data from a different URL occasionally.
the http_get() function returns a number, which you can use to check if the async event is getting the right data.

Save the http_get request in a variable:
Code:
get = http_get("http://mywebsite.com/generate.php");
Put this before the other code in the async http event:

Code:
if ds_map_find_value(async_load, "id") == get
{
  // rest of code
}
If that doesn't help, you could print out the content of the result, to see what it actually is.
 

FrostyCat

Member
async_load[? "status"] can also sometimes give 1 to indicate an in-progress request, where async_load[? "result"] would be missing. That needs to be checked for in addition to async_load[? "id"].

Create event:
Code:
ah_generate = -1;
Starting the request:
Code:
ah_generate = http_get("http://mywebsite.com/generate.php");
HTTP event:
Code:
if (async_load[? "id"] == ah_generate) {
  switch (async_load[? "status"]) {
    case 1: break;
    case 0:
      var map = json_decode(async_load[? "result"]);
      if (map != -1) {
        /* Further processing of map here */
        ds_map_destroy(map);
      }
    break;
    default:
      show_message("Cannot connect to server.");
    break;
  }
}
The HTTP event should always contain the following:
  • A check for async_load[? "id"] against a previous request ID
  • Checks for all 3 kinds of values for async_load[? "status"] (1, 0 and <0 as of the time of writing)
  • (if dependent on actual response output) Usage of async_load[? "result"] after confirming both async_load[? "id"] and async_load[? "status"]
Anything less is way too casual and asking for unexpected behaviour.
 
F

FuRyvok

Guest
So far it looks like its good, thanks for your help FrostyCat, but you should edit your reply, if anyone has the same problem as me, and don't understand whats going on.
Code:
if (map != -1) {
        /* Further processing of map here */
        ds_map_destroy(map);
}
To

Code:
if (map == -1) {
        /* Further processing of map here */
        ds_map_destroy(map);
}
 
Top