Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid 3 ajax calls?
    primarykey
    data
    text
    <p>I wrote some code that filters a province/state select field after you choose a country:</p> <pre><code> var cache = {}; function updateProvinceOptions($select, values, initial) { for(i in values) { $select.append('&lt;option value="'+values[i][0]+'"&gt;'+values[i][1]+'&lt;/option&gt;'); } $select.val(initial).trigger('change'); } $('&lt;select class="province" /&gt;').insertBefore('.province').change(function() { // insert select boxes beside hidden province inputs $(this).siblings('input.province').val($(this).val()); // update hidden input with current value }); $('.country').change(function() { var $countrySel = $(this); var $provSel = $countrySel.parent().parent().next().children('td').children('select.province'); var $provInput = $provSel.siblings('input.province'); var country = $countrySel.val(); var province = $provInput.val(); $provSel.empty(); if(country in cache) { updateProvinceOptions($provSel, cache[country], province); } else { $provSel.addClass('loading'); $.getJSON('/get-provinces.json', {'country':country}, function(provinces) { $provSel.removeClass('loading'); cache[country] = provinces; updateProvinceOptions($provSel, provinces, province); }); } }).trigger('change'); </code></pre> <p>It even caches the results so that if you, say, choose Canada, then US, and then Canada again, it doesn't have to hit the server for the list of Canadian provinces a second time. However, I'm displaying 3 of these on the page at the same time. When the page first loads, there's nothing in cache, so all 3 of em hit the server for a list of provinces because none of the ajax calls have returned yet. </p> <p>Is there a relatively simple way to tell it to "wait" if an ajax call for that country is already in progress? Or should I even bother?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload