javascript - PHP Ajax call to clear and populate a drop down menu -


hi have form on web page, example contains list of cars seen below:

 <select name = "car" id="cars" onchange="showform()">             <option value="0">toyota</option>             <option value="1">audi</option>             <option value="2">suzuki</option> </select> 

underneath dropdown have drop down models:

<select id="models" onchange="showform()">             <option value="0">r8</option>             <option value="1">quattro</option>             <option value="2">a6 hatchback</option> </select> 

however - wish second dropdown car models change when, user has selected different type of car brand.

i know can make select have onchange method, , can make ajax call create new array of models, - have no idea how existing models out of dropdown , populate dropdown new options. using php. eg of onchange script:

<script type="text/javascript">      function getmodels(obj){         var cartypeid = $(obj).attr('value');          $.ajax({             type: "post",             url: "/project/main/getmodels",             data: { 'cartypeid': cartypeid  },             success: function(msg){                //i don't know how put results select box?             }         });     }  </script> 

any ideas appreciated - php result array of arrays seen below:

[models] => array ( [0] => array ( [modelname] => r8 ) [1] => array ( [modelname] => a6 hatchback ) )  

first need update select like

<select name = "car" id="cars" onchange="getmodels(this.value)">         <option value="0">toyota</option>         <option value="1">audi</option>         <option value="2">suzuki</option> 

and model

<select name = "model" id="models" onchange="showform()">  </select>     <script type="text/javascript">      function getmodels(v){        // var cartypeid = $(obj).attr('value');          $.ajax({             type: "post",             url: "/project/main/getmodels",             data: { 'cartypeid': v  },             datatype:'json',             success: function(msg){                 html = '';               if(msg.model){                 for(i=0;i<msg.model.length;i++){                    html += '<option value="'+msg.model[i][model_id]+'">'+ msg.model[i][model_name] +'</option>';                 }                 $('select[\'name=model\']').html(html);              }              }         });     } $('select[name=\'car\']').trigger('change'); </script> 

now on php code think should push model id .. like

  <?php    //$results database result fetched    $models = array();    foreach($results $row){        $models[] = array(        'model_id' => $row['modelid'],        'model_name' => $row['modelname']      );     }     echo json_encode($models);    ?> 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -