Is this a problem (or a design pattern?) That I think is pretty common, so I hope this post can help others with a similar problem ....
I have a rare situation where a complex form should dynamically allow users to edit data that depends on other options that the user makes. I am using Ajax, jQuery with PHP and postgres as a database.
I figured out how to return data for a single record based on two values selected by the user using the jQuery Ajax technique (for this, Ajax is as weak as php); usually the return value will be one entry that my HTML form can process. But sometimes the return value will be two or three records. In this case, I need to dynamically add input fields and populate them with the returned data.
Here is the code in my form; the Fetch button accepts a Selected Marker value and a Selected LabID value to search for a dependent record that contains Allele_1, Allele_2 and Run date:
<fieldset>
<LEGEND><b>Edit Genotype</b></LEGEND>
<p>
<boldlabel>Selected Marker</boldlabel><input name=sel_marker length=15 DISABLED>
<boldlabel>Selected LabID</boldlabel><input name=sel_labid length=10 DISABLED><br>
<boldlabel>Allele_1</boldlabel><input id=allele1 name=allele_1 size=5 >
<boldlabel>Allele_2</boldlabel><input id=allele2 name=allele_2 size=5 >
<boldlabel>Run date</boldlabel><input id=run_date name=run_date size=10 >
<br>
</p>
<input type="button" name="fetch" id="fetchbutton" value="Fetch" sclass="btn">
<input type="button" name="save" value="Save" onclick="savegenotype()" class="btn">
<br>
</fieldset>
This is the javascript code associated with the Fetch button:
function fetchgenotype() {
var mndx = document.EditGenotype.marker.options[document.EditGenotype.marker.selectedIndex].value;
var sndx = document.EditGenotype.labid.options[document.EditGenotype.labid.selectedIndex].value;
$.post("fetchAlleles.php", {mndx: mndx, sndx: sndx},
function(result) {
i=0;
result.each(
a1='allele1_'||i.toString();
a2='allele2_'||i.toString();
r='rundate_'||i.toString();
$("#run_date").after(a1);
$("#run_date").after(a2);
$("#run_date").after(r);
)
}, "json");
return false;
}
Here is a separate PHP script that is part of Ajax that looks for related data:
$dbconnect = pg_pconnect("host=".$hostname." user=".$dbuser." dbname=".$dbname);
if (!$dbconnect) {
showerror(0,"Failed to connect to database",'fetchAlleles',16,"username=".$dbuser.", dbname=".$dbname);
exit;
}
$sql = "SELECT allele1, allele2, run_date FROM geno.genotypes WHERE markers_id=".$mndx." AND gsamples_id=".$sndx;
$fetchresult = pg_exec($dbconnect, $sql);
if ($fetchresult) {
$arr = pg_fetch_array($fetchresult, 0, PGSQL_NUM);
} else {
echo "(25) Failed to retrieve results.<BR>SQL: ".$sql."</br>";
}
echo json_encode($arr);
?>
}
, , ; , jQuery javascript .
a1 = 'allele1_' || i.toString();
jQuery-, , ...