0

I have this JavaScript code that creates a table, and puts in the rows and columns. I want to call this function, based upon some data in a database. So the amount of rows is based upon the amount of data in the database. My data in my database is a markscheme, I want the the table to fill depending upon the amount of questions are in the database

I have tried and here is my code:

hasLoaded = true;//page loaded set to true

<?php
  $query = "SELECT maxMark, criteria FROM mark ";
  $result = mysql_query($query);

  while ($result != null)
  { 
    addRow();//add row with everything in
  }
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
John Smith
  • 1,089
  • 3
  • 18
  • 37
  • makes little sense, you say js code when showing php. –  Mar 22 '12 at 19:52
  • possible duplicate of [Call php function from javascript](http://stackoverflow.com/questions/7165395/call-php-function-from-javascript) – g.d.d.c Mar 22 '12 at 19:53
  • @Dagon - it's not that it doesn't make sense, it's that the OP's understanding isn't quite fully developed yet. The two languages are handled at entirely different times. The PHP runs at the Server, and the JavaScript runs in the Browser. Mixing them in this way does not work. – g.d.d.c Mar 22 '12 at 19:54
  • i want to call a javascript function in php, with the php being inside javascript – John Smith Mar 22 '12 at 19:54
  • @Dagon is wrong, but the solution is terrible `while ($result != null) { echo "" }; // WORST IDEA EVER` – Jamund Ferguson Mar 22 '12 at 20:01

2 Answers2

2

The correct answer is json_encode your data from PHP and store it in a JavaScript variable like this.

<?php
  // populate the php rows array
  $rows = array();
  while ($row = mysql_fetch_assoc($result)) {
    $rows = array_push($rows, $row);
  }
?>
<script>
// populate the javascript rows array
var rows = <?php echo json_encode($rows); ?>;
for (var = 0; i < rows.length; i++) {
   addRow(rows[i]);
}
</script>
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
1

I would not recommend Jamund's solution, as it would require either inline javascript, or parsing your javascript files through PHP. I would recommend using an Ajax post in your javascript function to fetch the data from your server, and then populating from there.

$(document).ready(function(){
$.ajax({
 type: "POST",
 url: "yourscript.php",
 data:{param1: 'yourParam'},
 success: PopulateTable
 });
});

functionPopulateTable(data, status)
{
// Build Table with data
}

http://api.jquery.com/jQuery.ajax/ is a good place to start if you are using jQuery on your page.

Andrew Edvalson
  • 7,658
  • 5
  • 26
  • 24