[jQuery] A function I wrote that you might find useful (populateFieldsWithJson)
I needed a simple method to populate field names with corresponding
data from a database (for an "edit entry" interface). So I wrote the
following function, which accepts 3 arguments: the ajax get request
url, the form id, and new text for the form's submit button, if
required:
function populateFieldsWithJson(url, form, submit_text) {
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(json) {
$("#"+form+" input[type=text]").each(function() {
var fieldName = $(this).attr("name");
var getVal = "json."+fieldName;
var value = eval(getVal);
$(this).val(value);
var submit_button = $("#"+form+" input[type=submit]");
if (submit_text) submit_button.val(submit_text);
});
}
});
}
The request must return json data, with name/value pairs corresponding
to your form fields. Some example data might be: { "name": "Michael",
"phone": "555-1234" }
This would populate the corresponding text fields of your form (in
this example "name" and "phone"), with the specified data ("Michael",
"555-1234").