Francesco
Francesco

Reputation: 25259

Is there a way to async call external API without slowing down the entire website?

I have an e-commerce where I load eBay API at the end of the page with items related to the main product.

But I noticed that the request slows down the entire page load by 4 to 10 seconds.

I'd rather have the page loaded and THEN a module in the page with a loader, so by the time the user scrolls all the way down the eBay items are loaded. I know I could try this in JavaScript but, before coding it, I was wondering if PHP can handle asynchronous requests.

I'm currently using CURL. Here's my code:

$q = 'iphone'
$api     = 'https://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsAdvanced&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=remoteco-effectsb-PRD-a38ccaf50-f6906249&RESPONSE-DATA-FORMAT=JSON&REST-PAYLOAD&keywords=';
$url     = $api . $q;

$ch      = curl_init();
$timeout = 1;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$output  = curl_exec($ch);
curl_close($ch);

$array   = (array) json_decode($output);

Upvotes: 0

Views: 62

Answers (1)

Borian
Borian

Reputation: 622

After PHP finishes rendering your page, you can't receive additional data from the same script.

You can start background tasks, but can't receive the result with the same request.

Your best option would be to move the code to fetch related items to another PHP script and call that with Javascript.

That said there are ways to send chunked responses but are likely not the best option for you.

Upvotes: 1

Related Questions