1

I'm having a curiosity issue and don't seem to find the correct phrases for expressing what I mean, for a successful Google search query.

Some sites (that mostly do price queries) do an ajax query to something (let's assume it's php script) with user set criteria and the data doesn't get displayed all at once when the query is finished, but you see some parts being displayed from the response earlier (as I assume they become available earlier) and some later.

I'd imagine the ajax request is done to a php script which in turn queries different sources and returns data as soon as possible, meaning quicker query responses get sent first.

Core question:

How would such mechanism be built that php script can return data multiple times and ajax script doesn't just wait for A response?

I'm rather sure there's information about this available, but unfortunately have not been able to find out even by what terms to search for it.

EDIT:

I though of a good example being cheap flight ticket booking services, which query different sources and seem to output data as soon as it's available, meaning different offers from different airlines appear at different times.

Hope someone can relieve my curiosity.

Best,

Alari

Alari Truuts
  • 310
  • 4
  • 12

1 Answers1

1

On client side you need onprogress. See the following example (copied from this answer):

var xhr = new XMLHttpRequest()
xhr.open("GET", "/test/chunked", true)
xhr.onprogress = function () {
  console.log("PROGRESS:", xhr.responseText)
}
xhr.send()

xhr.responseText will keep accumulating the response given by the server. The downside here is that xhr.responseText contains an accumulated response. You can use substring on it for getting only the current response.

On the server side, you could do output buffering to chunk the response, e.g. like:

<?php
header( 'Content-type: text/html; charset=utf-8' );
for($i = 0; $i < 100; $i++){
    echo "Current Response is {$i} \r\n";
    flush();
    ob_flush();
    // sleep for 2 seconds
    sleep(2);
}
Community
  • 1
  • 1
Gogol
  • 3,033
  • 4
  • 28
  • 57