I have a HTML page that interactues with a PHP file using jQuery and AJAX, and I want to improve and implement few things.
I load the <select>-boxes with the response returned by the previus <select>-box. So I did a simple function to save some code. Here it is:
$(document).ready(function(){
$("#sex").click(function(){
getPHPdata("sex", "age");
});
$("#age").click(function(){
getPHPdata("age", "work");
});
$("#work").click(function(){
getPHPdata("work", "country");
});
$("#country").click(function(){
getPHPdata("country", "city");
});
function getPHPdata(oASelect, oFSelect) {
$("#" + oFSelect).empty();
$.ajax({
type: 'POST',
url: 'loadselect.php',
data: 'id=' + encodeURIComponent(oASelect) + "&p=" + encodeURIComponent($("#" + oASelect).val()),
dataType: 'json',
success: function(data){
for (var i = 0; i < data.length; i++) {
$("#" + oFSelect).append("<option>" + data[i] + "</option>");
}
}
});
};
});
Well, in this code I have only four <select>-boxes, but i'll need to use at least eight (all using the same parent as the code above). There is any way to optimize this or save more code?
My second question is:
When the length of the array returned by the PHP file is of only one element, then it'd call the function of its click event and load the next <select>-box because the user can only choose that option.
I don't know how what is the better way to do it, becouse if I control it in the php file, then I don't know how send the response and process it in the html file.
I hope I was clear in my explanation. Any help, advice or example would be appreciated. If you need more details let me know and I'll edit the post.