Rohan
Rohan

Reputation: 314

ajax retrieve huge data from server

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.

Upvotes: 0

Views: 1373

Answers (1)

Jason
Jason

Reputation: 965

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.

Upvotes: 2

Related Questions