My English is not very good, so I will just write some things that I have.
1: You want to get a dropdown list depend on the index 2: You want to shown selected options depend on the id
FirstLy, your codes are terrible. The php codes are just trying to get the data you need, why did you mix with html?
Let's try to solve the first question, we get a drop-down list. You should just let the PHP code get the data you need, so you better change your show_result php function, I would like to write like this:
public function show_result(){ $tmpData = array(); $i = 0; $query = mysql_query($this->_query); while($result = mysql_fetch_array($query)){ $id = $result[$this->_fields[0]]; $enity_name = $result[$this->_fields[1]]; $tmpData[$i]['id'] = $id; $tmpData[$i]['name'] = $enity_name; } return $tmpData; //here it saves data which you want to shown in drop down list }
then at the end of the ajax.php file,
$obj = new AJAX; echo json_encode($obj->show_result());
Then in a js script try to parse the data you get from ajax.php and this is a json string, it contains identifiers and names. create dropdown selector options.
function load_options(id,index){ $("#loading").show(); if(index=="state"){ $("#city").html('<option value="">Select city</option>'); } $.ajax({ url: "ajax.php?index="+index, //do not pass id complete: function(){$("#loading").hide();}, success: function(data) { var jsonObj = eval('('+data+')'); var selected = false; var options = ''; for(jsonObj in eachData){ if(eachData.id == id) selected = true; // shown selected if it the right option you want to see options += '<option value="'+eachData.id+'"'+selcted?"selected":""+'>'+eachData.name+'</option>'; selected = false; } $("#"+index).html(options); } }) }
then you will receive a drop-down list at your request. I just write these codes to guide you, and I did not debug or test them, just try: get the data from php, show them as html on the page.
So thatโs it. And again, sorry for my scary English (I speak good Chinese :))