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.