There are two related option fields in the form for filtering cars by make and model: mark -> model . When choosing a brand models are loaded. The problem is that the stamps are not podgrudyutsya from the server with in advance, but only at the time of clicking on the first field with marks using $('#mark').focus , and it turns out that every click on the drop-down menu of marks is sent a request, which creates an extra server load.

How can I fix this problem without changing the server code but only by modifying the logic of ajax requests?

The form itself:

 <div> <select id="mark" name="mark" data-url="get_all_proposes/get_all_marks"> <option value="">Select mark</option> </select> </div> <div> <select id="model" name="model" data-url="get_all_proposes/get_model_by_mark"> <option value="">Select model</option> </select> </div> 

js code:

 $(document).ready(function () { //Get marks set. $('#mark').focus(function(event) { $.ajax({ url : 'get_all_proposes/get_all_marks', type : 'get', dataType: 'json', success: function (data) { var select = $('#mark'); $.each(data, function(index, value) { var optionMark = $('<option>'); optionMark.val(value).text(value).appendTo(select); }); } }); }); //Get models set. $('#mark').change(function() { $.ajax({ url : 'get_all_proposes/get_model_by_mark', type : 'get', data : { 'mark' : this.value }, dataType: 'json', success : function(data) { var optionModel = $('#model'); $.each(data, function(index, value) { optionModel.append($('<option>').val(value).text(value)); }); } }); }); }); 
  • look away - Facebook GraphQL and Netflix Falcor - Mikhail Vaysman

1 answer 1

If the list of stamps is fiscated and does not depend on other parameters (which is most likely the case), then you can fill it in immediately after creating the page:

 $(document).ready(function () { //Get marks set. $.ajax({ url: 'get_all_proposes/get_all_marks', type: 'get', dataType: 'json', success: function (data) { var select = $('#mark'); $.each(data, function (index, value) { var optionMark = $('<option>'); optionMark.val(value).text(value).appendTo(select); }); } }); //Get models set. $('#mark').change(function () { $.ajax({ url: 'get_all_proposes/get_model_by_mark', type: 'get', data: { 'mark': this.value }, dataType: 'json', success: function (data) { var optionModel = $('#model'); $.each(data, function (index, value) { optionModel.append($('<option>').val(value).text(value)); }); } }); }); });