Dynamic dropdowns using ajax, sql and php

I have some code that works well. It fills out the dropdown lists depending on the previous list, but there is a problem. On the html form, the <option value =""> field displays "id", which is a numeric value instead of "name". Can someone please tell me how it can display "name" instead of value. The actual problem is that when saving data in the sql database, it saves the corresponding "id" of the country or state or city, and not its "name".

This is the code I'm using. I tried changing the last line in ajax.php echo "<option value='$entity_id'>$enity_name</option>"; on echo "<option value='$entity_name'>$enity_name</option>"; , but then dynamic drop-down lists do not work, because they depend on the "id". Many thanks for your help.

ajax.php

 <?php /* File : ajax.php * Author : Manish Kumar Jangir */ class AJAX { private $database = NULL; private $_query = NULL; private $_fields = array(); public $_index = NULL; const DB_HOST = "localhost"; const DB_USER = "admin"; const DB_PASSWORD = "admin"; const DB_NAME = "disciples"; public function __construct(){ $this->db_connect(); // Initiate Database connection $this->process_data(); } /* * Connect to database */ private function db_connect(){ $this->database = mysql_connect(self::DB_HOST,self::DB_USER,self::DB_PASSWORD); if($this->database){ $db = mysql_select_db(self::DB_NAME,$this->database); } else { echo mysql_error();die; } } private function process_data(){ $this->_index = ($_REQUEST['index'])?$_REQUEST['index']:NULL; $id = ($_REQUEST['id'])?$_REQUEST['id']:NULL; switch($this->_index){ case 'country': $this->_query = "SELECT * FROM countries"; $this->_fields = array('id','country_name'); break; case 'state': $this->_query = "SELECT * FROM states WHERE country_id=$id"; $this->_fields = array('id','state_name'); break; case 'city': $this->_query = "SELECT * FROM cities WHERE state_id=$id"; $this->_fields = array('id','city_name'); break; default: break; } $this->show_result(); } public function show_result(){ echo '<option value="">Select '.$this->_index.'</option>'; $query = mysql_query($this->_query); while($result = mysql_fetch_array($query)){ $entity_id = $result[$this->_fields[0]]; $enity_name = $result[$this->_fields[1]]; echo "<option value='$entity_id'>$enity_name</option>"; } } } $obj = new AJAX; ?> 

index.html

 <html xmlns="http://www.w3.org/1999/xhtml"><head profile="http://gmpg.org/xfn/11"> <head> <title>Country State City Dependent Dropdown using Ajax</title> <script type="text/javascript" src="jquery-1.5.2.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ load_options('','country'); }); function load_options(id,index){ $("#loading").show(); if(index=="state"){ $("#city").html('<option value="">Select city</option>'); } $.ajax({ url: "ajax.php?index="+index+"&id="+id, complete: function(){$("#loading").hide();}, success: function(data) { $("#"+index).html(data); } }) } </script> </head> <body> <div style="width:800px; margin:auto;padding-top:100px;"> <h1>Country,State,City dynamic dependent dropdown using Ajax and Jquery</h1> <form> <label>Select Country</label> <select id="country" name="country" onchange="load_options(this.value,'state');"> <option value="">Select country</option> </select> &nbsp;&nbsp;&nbsp; <label>Select State</label> <select id="state" name="state" onchange="load_options(this.value,'city');"> <option value="">Select state</option> </select> &nbsp;&nbsp;&nbsp; <label>Select city</label> <select id="city" name="city"> <option value="">Select City</option> </select> <img src="loader.gif" id="loading" align="absmiddle" style="display:none;"/> </form> </div> </body> </html> 
+4
source share
2 answers

You can get a script to do what you want,

  • showing an identifier as a data attribute. โ†’ Ajax->show_result()
  • using this attribute for id parameter in ajax call. โ†’ load_options()
  • pass the whole <option> element to load_options()

this.value is not this.value for an ajax request with a hit of cahages because it is a name, but this still has an identifier as a data attribute.

 <select id="country" name="country" onchange="load_options(this, 'state');"> <option value="">Select country</option> </select> 

since the id parameter is an option element from the form, we need to compensate in order to get the correct code.

 function load_options(id,index){ ... that = $(id).find(":selected"); id = that.data('realid'); $.ajax({ url: "ajax.php?index="+index+"&id="+id, ... 

let the value attribute keep the name, but keep the identifier.

 public function show_result(){ ... while ($result = mysql_fetch_array($query)){ ... printf( '<option data-realid="%s" value="%s">%s</option>', $entity_id, $enity_name, $enity_name ); 

This should answer your question, and depending on how the form is submitted and saved, it may solve your problem. I doubt it, however, because the part that you neglected to show us is most likely waiting for the state and city identifier, not their names.

+1
source

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 :))

+1
source

Source: https://habr.com/ru/post/1215904/


All Articles