I'm getting data from a json file, accessed from URL,and the loading time is really long. However this website(https://gw2efficiency.com/) is actually getting same data, but some way manages to show them only when they are ready, and i would like to do it too.
I haven't found any clear way of doing this, i saw it might be an AJAX call but never used that.
this is where i show the data
<header>
<?php require 'getbag.php'?>
</header>
<body>
<div>
<span>Argent flat actuel: </span><br>
<?php echo " ".$gold ?><img alt="gold" src="gw2/images/gold_coin.png"><?php echo " ".$silver ?><img alt="silver" src="gw2/images/silver_coin.png"><?php echo " ".$copper ?><img alt="copper" src="gw2/images/copper_coin.png">
</div>
</body>
And this is the file i call to get the data from the json file
getbag.php
<?php
$apikey = '<apikey>';
$headers = array(
'Accept-Language: fr',
'Authorization: Bearer '.$apikey.'',
);
$url='https://api.guildwars2.com/v2/account/wallet';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$array1 = json_decode($result, true);
$value[] = $array1[0]['value'];
$id[] = $array1[0]['id'];
$total=$value[0];
$copper = substr($total, -2, 2);
$silver = substr($total, -4, 2);
$gold = substr($total, 0, -4);
?>
I would like to see the html page instantly, if you have any idea how :).
AJAX is a simple way to make a request to to a server asynchronously from the frontend(javascript). So in your example you wish to hit the guildwars endpoint. As you can see in the code below, I make an ajax request to your endpoint, set the same headers and define a callback for when the response is successful. console.log(JSON.parse(this.responseText)); will log the response to your browsers console. Then it's just a matter of accessing the javascript object.
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// view the this.responseText in your browser console log
console.log(JSON.parse(this.responseText));
}
};
xhttp.open("GET", "https://api.guildwars2.com/v2/account/wallet", true);
xhttp.setRequestHeader("Accept-Language", "fr");
xhttp.setRequestHeader("Authorization", "Bearer <apikeyGoesHere>");
xhttp.send();
}
loadDoc();
</script>