-2

I have a PHP page that processes some information when a button is pressed. One of this information is to process a query. I then want the results of the query to be put into a table in another page. I know how to put query results into a table, but I don't know how to pass them row by row to a table on another page. Can anyone help or point me in the right direction?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
M9A
  • 3,168
  • 14
  • 51
  • 79
  • why can't you query the information on one page and retrieve the information from another? – Nick Fury Nov 18 '12 at 20:56
  • I dont know how I can pass it row by row...so the table on the other page would have the correct results – M9A Nov 18 '12 at 20:58

1 Answers1

1

If I understood this correctly, you'll need AJAX (and, by requirement, JavaScript) for this. What you want to do is call your generation function and have it return a format that you can parse (JSON, XML, you name it).

From there, you'll append it to your table using JavaScript's DOM manipulation functions.

The generation part

Assume that you're getting your data in an array format as follows:

$row = array('column 1','column2');

You'll be getting tons of rows like these, or just one - we'll write the script to handle both cases without requiring a rewrite. Every time you get a row, add it to a non-associative array , call it $RowArray. So, on every row, you'll be calling $RowArray[] = $row;.

You now have the PHP side almost done - all you need to do now is to echo it back to the client. Make sure you echo nothing else but this: echo json_encode($RowArray);. This will format and serialize your array to be a perfect JSON object.

The JavaScript side

We'll assume jQuery for simplicity. Your aim will be to read the JSON object and add rows to a table. We'll assume that the table has ID #MyTable.

The AJAX call is done as follows:

$.ajax({
  url: "your_url.php",
  dataType: "json",
  type: "post",
  success: function(d) {
     // Your code here
  }
});

The success handler will be triggered when the object has been successfully parsed, and the variable d will be the object. This object will be a JavaScript array where each element is an object. All you need to do now is to loop through d and create a row per entry!

success: function(d) {
   for(var i=0; i < d.length; i++) {
      var newRow = $("<tr></tr");
      for (var k in d[i]) {
          newRow.append($("<td></td>").text(d[i][k]));
      }
      newRow.appendTo($("#MyTable"));
   }
}

Voila, dynamic AJAXified table in six lines!

Sébastien Renauld
  • 19,203
  • 2
  • 46
  • 66