Josh Hernandez
Josh Hernandez

Reputation: 25

How to send data in ajax with dependent drop-down

I Have already set the first value from the first combo-box now i need to send the second variable from second combo-box and receive it in the same php file here is the Ajax:

$(document).ready(function(){
   $(".rutas").change(function(){
     var id=$(this).val();
     var dataString = 'id='+ id;
     $.ajax({
       type: "POST",
       url: "asientos.php",
       data: dataString,
       cache: false,
       success: function(html){
          $(".asientos").html(html);}  
       }); 
   }); 
});
</script>

Here is the first html combo-box this is functioning perfectly:

<select name="rutas" class="rutas" >
   <option value="">Seleccione Ruta</option>;
   <?php   include 'rutas.php';   ?>
</select>

Here is the second html combo-box that i want to get the value from and send it to the same php file as the first:

Clase: <select name="clase" class="clase">
   <option value="A">Clase Ejecutiva</option>;
   <option value="B">Clase Media</option>;
   <option value="C">Clase Economico</option>;
</select>

Any help would be appreciated, Thank you!

Upvotes: 2

Views: 2443

Answers (1)

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

Send multiple values to ajax use object

var data = {field1: "value1", field2: "value2"};

In your case, you should use form

<form id="myForm">
<select id="select1"></select>
<select id="select2"></select>
</form>

JavaScript code.

$(document).ready(function(){
  $('#myForm').submit(function(event){
     event.preventDefault();
     var data = {field1: $("#select1").val(), field2: $("#select2").val()};

     //Ajax code should be here
     $.ajax({
         type: "POST",
         url: "asientos.php",
         data: data,
         cache: false,
         success: function(html){
            $(".asientos").html(html);}  
         }); 
     }); 
   });
});

Edit : As per the comments

function ajaxCall(url, data){

     //Ajax code should be here
     $.ajax({
         type: "POST",
         url: url,
         data: data,
         cache: false,
         success: function(html){
            $(".asientos").html(html);}  
         }); 
     }); 
}

On each select change method you can call this ajax function and populate your drop-down.

$(".rutas").change(function(){
    ajaxCall('demo.php', '10');
});

Upvotes: 1

Related Questions