If you're looking for a simple way to accomplish this, consider using a PHP file to return JSON data. For example, create a file called 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 need to use document.write and have fields with ids like
<input type="text" id="field1" />
, you can access them using jQuery:
$("#field1").val()
.
Here is an example including HTML. Assuming you have two fields named field1
and field2
:
<!DOCTYPE html>
<html>
<head>
<title>Example</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>
If you want to populate data dynamically as you construct the HTML, you can still use a PHP file to return JSON and insert it directly into the value
attribute.