从数据库查询结果中逐步提取数据

I'm using db_query() to select data from a PostgreSQL database. Is there a way to incrementally extract data from a query result created from an AJAX-linked PHP file? Here's an example attempt that uses a simplified variable assignment:

PHP file:

<?php
if (isset($test_var)) {
  echo $test_var;
}
else {
  echo "undefined";
  $test_var = "Variable has been set";
  //$test_var = db_query("...");
}

Source (main page):

<input type="submit" name="submit" value="Submit" onclick='click_query()'/>
<div id="myDivD" style="display: none;"></div>

<script>
function click_query() {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } 
  else { 
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("myDivD").innerHTML=this.responseText;
      alert(this.responseText);
    }
  }
  xmlhttp.open("GET","/sites/all/modules/afb/afb.php, true);
  xmlhttp.send();
}
</script>

I was optimistic this might work, but not terribly surprised that it failed. Only "undefined" was returned.

I've previously attempted doing everything client side (with PHP/Javascript) which resulted in slow load times. My dataset has since increased substantially (nearly x100). I'm trying to perform more processing server-side with AJAX. Ideally, I'd be able to run a custom SQL query, dictated by a user, a single time and pull select rows from the query result to populate a page. However, I haven't been able to figure out a way to keep the SQL query results saved in memory without passing everything to the client's side. This would make re-running the query necessary, which would produce impractical load times.

The queries are complex enough that saving specific query results server-side isn't realistic. Unless perhaps data could be compressed and incrementally decompressed client side to save memory and maximize performance? Is there a way to keep the PHP file linked via AJAX until the main page is refreshed or changed (to prevent losing assigned variables)? Although I don't have much experience in jQuery, I am also interested in possible jQuery solutions (which seems to be the preferred method for implementing AJAX).