Wednesday, August 15, 2012

JSON Issues when Upgrading from jQuery 1.3.2 to jQuery 1.7.2

On the tails of my recent post about the jQuery 1.8 release comes this example of some of the 'breakage' that can occur when changing jQuery versions. Granted this is an older issue, but if you are on an older version of jQuery (pre 1.5), then you are likely to get hit with this issue whenever you upgrade to a newer version.

In jQuery 1.3.2 and older, $.getJSON is very forgiving of malformed JSON and even inappropriate mime-types. In jQuery 1.4+, things are a bit more strict.

For example, in jQuery 1.3.2 you are able to do this:

Code Snippet:
$.getJSON("test.js", function(json) {
   alert(json);
 });

Remote JSON:
[ 

  {

   value: "blah",

   bar: "none",

   url: "/blah.html",

   desc: "foo"

  },


  {

   value2: "blah",

   bar2: "none",

   url2: "/blah.html",

   desc2: "foo"

  },

]

In jQuery 1.4+, this will not cut it. Your JSON will need to be well-formed and you could also switch over to using $.ajax for further flexibility.

Code Snippet:
$.ajax({
  url: 'ajax/test.json',
  dataType: 'json',
  data: data,
  success: callback
});

Remote JSON (w/ proper mime-type):
[{"value": "blah","bar": "none","url": "/foobar.html","desc": "foo"},{"value2": "blah","bar2": "none","url2": "/foobar.html","desc2": "foo"}]

While you may not have any custom implementations using JSON, don't assume you are home-free. jQuery UI Autocomplete, for example, could break when upgrading from 1.3.2 to 1.4+. That is because it uses $.getJSON behind the scenes instead of $.ajax. If your JSON is well-formed, you should have no issues, but using $.ajax will allow you to return the JSON, process it, and bring it into conformity all before jQuery UI autocomplete knows the difference.

For example, jQuery 1.3.2 may play nice with this:

$( "#search" ).autocomplete({
  source: "search.php",
  minLength: 2
});

However, jQuery 1.4+ may require something like this if you need to get your hands on the JSON before jQuery UI autocomplete does:

$( "#search" ).autocomplete({
  source: function(request, response) {
    $.ajax({
      dataType: 'text json',
      success: function(data) { response(data); }
        url: 'search.php?term=xyz',
        });
    },
  minLength: 2
});

No comments:

Post a Comment