0

My ajax code is

function senddata()
{
    var ajaxRequest;  // The variable that makes Ajax possible!

    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function()
    {
        if(ajaxRequest.readyState == 4)
        {
            document.getElementById("showdata").innerHTML=ajaxRequest.responseText;
        }
    }

    ajaxRequest.open("GET", Handler.php?key=" + value, true);
    ajaxRequest.send(null); 
}

I have huge amount of data that gets retrieved through ajax. Now when i call this function, it takes much time to show data. I want here is that as the data gets retrived, it should be displayed on the screen. No need to show whole retrieved data only when everything is fetched but display data as it gets fetched.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Rohan
  • 304
  • 4
  • 16
  • possible duplicate of [Accessing partial response using AJAX or WebSockets?](http://stackoverflow.com/questions/7952448/accessing-partial-response-using-ajax-or-websockets) – Barmar Aug 23 '14 at 05:48
  • fetch data page by page(ex. limit 100) and append – Buddhi Aug 23 '14 at 06:06

1 Answers1

2

You're going to want to approach this with the same style of thinking as if you were implementing a pagination system.

I cannot see your Handler.php code, so it might make things difficult as we need to edit things in there.

  1. Make Handler.php accept limit and offset or page query var(s)
  2. Add the appropriate code in your PHP to handle that (and the case where none are provided, don't just sent everything! default limit to 10 and offset to 0.)
  3. Functionalize your ajax request and make it paginate:

    function getdata(limit, offset)
    {
         limit  = limit || 10;
         offset = offset || 0;
    
         var ajaxRequest;  // The variable that makes Ajax possible!
    
         // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function()
        {
           if(ajaxRequest.readyState == 4)
           {
               document.getElementById("showdata").innerHTML=ajaxRequest.responseText;
    
               // make Handler.php send 'end' when no results have been returned
               if (ajaxRequest.responseText && ajaxRequest.responseText != 'end') {
                 getdata(limit, offset + limit);
               }
           }
        }
    
       ajaxRequest.open("GET", Handler.php?key=" + value + '&limit=' + limit + 
         '&offset=' + offset, true);
       ajaxRequest.send(null); 
    }
    
    getData();
    

Just make sure Handler.php sends end when there is no more data.

Jason
  • 955
  • 9
  • 9