I'm currently working on my first Wordpress plugin a I want to get JSON Data from a Webserver via a GET request. I already tried some code like this: https://stackoverflow.com/a/36780287/4460483 but it's not what I'm looking for.
Also jquery tells me: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
So the problem is that the data somehow doesn't load fast enough and the page can't load. The reason is that you need to directly return a result for a shortcode, right? But I guess that takes too much time. So what is the best way to make GET requests without freezing the thread building the page (in PHP)? Is there somehow Events to do something like that?
My current code looks somehow like this:
function stats_shortcode($atts)
{
$attributes = shortcode_atts(array(
'player_name' => 'Default'
),$atts);
extract($atts);
$url = 'https://url/to'.$attributes['playername'];
$mh = curl_multi_init();
// Build the individual requests, but do not execute them
$chs = [];
$chs['ID0001'] = curl_init($url);
foreach ($chs as $ch) {
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true, // Return requested content as string
CURLOPT_SSL_VERIFYPEER => false, // Don't save returned headers to result
CURLOPT_CONNECTTIMEOUT => 10, // Max seconds wait for connect
CURLOPT_TIMEOUT => 20, // Max seconds on all of request
CURLOPT_USERAGENT => 'Robot YetAnotherRobo 1.0',
]);
// Add every $ch to the multi-curl handle
curl_multi_add_handle($mh, $ch);
}
// Execute all of queries simultaneously, and continue when ALL OF THEM are complete
$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running);
// Close the handles
foreach ($chs as $ch) {
curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
$profile = json_decode($responses['ID0001']);
return "<div><span>$profile->{'data'}</span></div>"
}
function stat_shortcodes_init()
{
add_shortcode('stats', 'stats_shortcode');
wp_register_style('StatStylesheet', plugins_url('styles.css', __FILE__));
wp_enqueue_style('StatStylesheet');
}
add_action('init', 'stat_shortcodes_init');
This somehow works local (when I wait long enough), but not on my server.