fabiobh
fabiobh

Reputation: 779

Async requests with Php Guzzle are not working async

I create the code below to make an async request to get data from an API.

<?php
require 'vendor/autoload.php';
$url = "https://pucminas.instructure.com/api/v1/";

$client = new GuzzleHttp\Client(['base_uri' => $url]);

$headers = [
    'Authorization' => "Bearer 11111~dsgffdhstggfjsdhf",
    'Accept'        => 'application/json',    
];

$course_id = "2242";
set_time_limit(300);

$promise = $client->getAsync( 'courses/'.$course_id.'/students/submissions?student_ids[]=all&grouped=true&post_to_sis=false&enrollment_state=active&include[]=user&include[]=assignment&include[]=total_scores&per_page=1000', ['connect_timeout' => 600, 'headers' => $headers]);

$promise
->then(function ($response) {
echo 'Got a response! ' . $response->getStatusCode();
});

?>
<h2>Reports</h2>

I suppose when I load the page it will show the text "Reports" in the page and after getting the content from the API(which needs at least 60 seconds), it will show the message "Got a response", but it won't work that way.

First, the page loads the content from the API and only after that show the text "Reports" and "Got a message" at the same time.

I want the text "Reports" appear instantly when I load the page, and the text "Got a response" only when the data is loaded from the API.

How can I do that?

Upvotes: 0

Views: 504

Answers (1)

touson
touson

Reputation: 154

You can only send a single response from a PHP script i.e. your browser requests a page, the PHP server builds that page and sends it back. The PHP server can't then 'push' an update of the page to your browser as HTTP is stateless.

To achieve the functionality you want you need to write some javascript which will call a PHP script to start the guzzle async promise. This promise would then write the result to a file (or database) when the promise is complete.

You then need a second javascript function which continually checks a second php script. The second PHP script would check the contents of the file (or database entry etc) and return the result.

You might be better to look at something like Axios and lose the PHP altogether

https://www.npmjs.com/package/axios

Upvotes: 1

Related Questions