get data from mysql database to use in javascript get data from mysql database to use in javascript ajax ajax

get data from mysql database to use in javascript


Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,

$result = mysql_query("SELECT field_name, field_value                       FROM the_table");$to_encode = array();while($row = mysql_fetch_assoc($result)) {  $to_encode[] = $row;}echo json_encode($to_encode);

If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().

Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then

<!DOCTYPE html><html>  <head>    <title>That's about it</title>  </head>  <body>    <form>      <input type="text" id="field1" />      <input type="text" id="field2" />    </form>  </body>  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>  <script>    $.getJSON('data.php', function(data) {      $.each(data, function(fieldName, fieldValue) {        $("#" + fieldName).val(fieldValue);      });    });  </script></html>

That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.


To do with javascript you could do something like this:

<script type="Text/javascript">var text = <?= $text_from_db; ?></script>

Then you can use whatever you want in your javascript to put the text var into the textbox.


Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?

  1. Send AJAX request to php script
  2. PHP script processes request and builds table
  3. PHP script sends response back to JS in form of encoded HTML
  4. JS takes response and inserts it into the DOM