How to start flushing/printing out a curl request on to go.



  • Hello,
    I want to print/echo out results I am getting from a JSON file on the go as soon as it loaded the first result. I am grabbing multiple JSON files and therefore can take some time for it to load the full page.

    For now I have an AJAX script that calls my PHP script and loads it in the page. My idea here is that the script and or via AJAX starts flushing out the results when it is loading the data.

    Eventually I'd like to get rid of the spinner loader and start printing out the results right away as soon as it grabbed 1 item fully from my curl request. The spinner will we replaced by a skeleton loading effect.

    Here is my request.php file:

    $resultsAPI = "https://www.example.com/api/results.json? 
    app_id=$app_id&token=$token&page=1&limit=10";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $resultsAPI);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json;api_version=2' ));
    $resp = curl_exec($curl);
    curl_close($curl);
    $results = json_decode($resp, true)['results'];
    
    foreach ($results as $key=>$resultImage) {
        $resultImage= "$resultImage[images]?app_id=$app_id&token=$token";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $resultImage);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $resp = curl_exec($curl);
        curl_close($curl);
        $image = json_decode($resp, true);
        $results[$key]['image1'] = $image['image1'];
    }
    
    echo '<div class="card"><ul>';
    foreach ($results as $result) {
    echo '<li>';
    echo '<span><p>'.$result['title'].'</p></span>';
    echo '<span><p>'.$result['description'].'</p></span>';
    echo '<span><img src="'.$result['image1'].'"></span>';
    echo '</li>';
    }
    echo '</ul></div>';
    

    And here is my index.html file:

    <div class="spinner-border" role="status">
    <span class="sr-only">Loading...</span>
    </div>
    
    <div class="update_panel"></div>
    
    <script>
    $('.spinner-border').show();
    $.ajax({
    url: 'request.php',
    type: 'post',
    success: function(data) {
    $('.update_panel').html(data);
    $('.spinner-border').hide();
    },
    error: function() {
    alert("Something went wrong!");
    }
    });
    </script>
    

    Any help here would be appreciated.

    --edit--
    This image is exactly what I am looking for what the script should do. I can add the syle/skeleton loading effect later.
    alt text


Log in to reply