Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .ajax() request not firing

I'm trying to make an AJAX call to my web server to pull down information about a city.

  • I have a select drop down on the page, populated with 3 values: [blank], "New York, NY", and "Ann Arbor, MI"
  • When an item is selected, the city's name is reformatted: spaces are turned into '-'
  • Then .ajax() is fired to "/data/[city]"
  • When the server responds, it calls alert() with a JSON object it retrieved.

Code:

$( document ).ready(function() {
  $('#city').change(function () {
    var city = $.trim($(this).val()).replace(/ /g,"-");
    if(city.length > 0)
    {
      var url = "/data/cities/" + city;
      $.ajax({
        url: url,
        context: document.body,
        dataType: 'json'
      }).done(function(data) {
        alert(data);
      });
    }
  });
});

For some reason, the .ajax() call refuses to fire on occasion. The outgoing HTTP request is never made when url equals:

  • /data/cities/New-York,-NY

However, it fires successfully when url equals:

  • /data/cities/New-York-NY (no comma)
  • /data/cities/New-York,NY (no dash)
  • /data/cities/New-York,-NYC (additional character)
  • /data/cities/Ann-Arbor,-MI (similar format)

I have verified:

  • The browser makes no outgoing HTTP request when it 'fails' (as checked via Chromium's Network tab)
  • The web server receives the HTTP requests for all the URLs except this problematic one
  • There are no Javascript errors on the page

Am I missing something obvious? This seems really weird that .ajax() wouldn't fire for this one specific URL...

EDIT:

Added an error callback to the .ajax() request. It is failing with an error of state = "rejected" and statusText = "error".

As requested, the <select> tag on the page:

<select id="city">
  <option value=""></option>
  <option value="New York, NY">New York, NY</option>
  <option value="Ann Arbor, MI">Ann Arbor, MI</option>
</select>
like image 687
David Elner Avatar asked Oct 03 '22 08:10

David Elner


1 Answers

By default, unless you used $.ajaxSetup for default settings you're not showing us, you're using the GET method. As you're not specifying an explicit value for cache, and its default value is true according to jquery spec (api.jquery.com/jQuery.ajax), your browser might still be working with an earlier (cached) response (even if the source code you see in the browser is up-to-date). I'd suggest using POST (if you an and if the server allows) and/or specifying cache: false explicity in the $.ajax({...}) call, just to rule any funny stuff out.

(copy/pasted from my comment as requested by the asker of the question)

like image 162
UweB Avatar answered Oct 12 '22 12:10

UweB