I'd like to make a form containing a couple of input fields. While typing something in these fields, a dropdown has to appear containing the matching records from a MySQL database. Following is the Javascript-code:
<script type="text/javascript">
$(function() {
$("#sampleprep, #quantity, #sampletype, #organism").autocomplete({
response: function(event, ui) {
try {
// ui.content is the array that's about to be sent to the response callback.
if (ui.content.length === 0) {
$("#"+event.target.id+"-empty-message").text("No results found");
} else {
$("#"+event.target.id+"-empty-message").empty();
//$("#"+event.target.id+"-empty-message").text(event.target.id);
}
} catch(err) {
error = "Error 1: "+err.message;
alert(error);
}
},
source: function(request, response) {
try {
var target_id = "sampletype"; <====
$.ajax({
url: "list_"+target_id+".php", <====
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
} catch(err) {
error = "Error 2: "+err.message;
alert(error);
}
},
minlength: 1
});
});
</script>
As you can see, there are 4 input fields using this code:
- sampleprep
- quantity
- sampletype
- organism
Each input field corresponds to it's own database table. I made 4 PHP-files to get the matching data. Filenames are:
- list_sampleprep.php
- list_quantity.php
- list_sampletype.php
- list_organism.php
My problem is indicated by the arrow <====
. Right now, the url is fixed to list_sampletype.php
. I'd like to make this dynamic, but I can't figure out how to get the id of the inputfield into the ajax-call. I tried event.target.id
, which is working in the first function, as well as some other things, but nothing returned what I want.