简体   繁体   中英

Jquery get values from select boxes and make AJAX call

I have multiple select boxes, where I want to get the value of each selected option and make an AJAX call based on the selected options. How can I achieve that?

I have this so far:

$('select[name="restaurant_chosen"]').on('change', function() {
    var restaurant_id = $(this).val();
});

$('select[name="date_chosen"]').on('change', function() {
    var date_chosen = $(this).val();
});

$.ajax({
   type: 'GET',
   url: '/api/' + restaurant_id + '/' + date_chosen +
   success: function(data) {
     console.log(data)
   }, 
   error: function(data){
    console.log('error')
  }
 });

the 2 variables restaurant_id and date_chosen I get the error not defined . What am I doing wrong?

And that is how it should be. You're declaring your variable within a private function context, which you cannot (and must not) access from the outside.

Simple solution, move the declaration of your two variable out of the onchange event handlers (make it more global).

var restaurant_id;
    date_chosen;

$('select[name="date_chosen"]').on('change', function() {
   date_chosen = $(this).val(); // skip the var here
});

 function sendToServer(values, onSuccess, onError){ var restaurant_id, date_chosen; //here fill restaurant_id and date_chosen using values $.ajax({ type: 'GET', url: '/api/' + restaurant_id + '/' + date_chosen, //replace the plus by a comma success: function(data) { onSuccess(data); }, error: function(data){ onSuccess(data); } }); } $('select').on('change', function() { var values = []; $('select').each(function(index){ v = $(this).val(); n = $(this).attr("name"); values.push( {"name":n, "value":v} ); }); console.log("values: ", values); sendToServer(values, function(data){ console.log(data); }, function(data){ console.log('error', data); } ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="brand"> <option value="volvo">Volvo</option> <option value="audi">Audi</option> </select> <select name="color"> <option value="red">Red</option> <option value="blue">Blue</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM