0

I'm trying to get my error function called when an external json fails to load.

This works fine with .getJSON, but doesn't with .ajax. Can anyone take a look at the code and tell me if I missed something?

JSfiddle here: http://jsfiddle.net/8C7Hb/

$.getJSON( "http://foo.com/bar.json", function() {
    $('#method1_result').html('Success');
}).fail(function() { $('#method1_result').html('Fail'); });

$.ajax({
    url: "http://foo.com/bar.json",
    dataType: "jsonp", 
    success: function(data) {
         $('#method2_result').html('Success'); 
    },
    error: function() {
        $('#method2_result').html('Error');
    }
}).fail(function() { $('#method2_result').html('Fail'); });

Thank you.

  • `dataType` should be `json`, as a sidenote. – jAndy Jun 18 '13 at 13:46
  • @jAndy : actually i'm trying to get jsonp to fail correctly. –  Jun 18 '13 at 13:47
  • 1
    then you're comparing apples with oranges. `getJSON()` will also set the dataType to `json`. `jsonp` is a whole different story. – jAndy Jun 18 '13 at 13:48
  • 1
    you should read this http://stackoverflow.com/a/2067584/1385672 the last paragraph – wirey00 Jun 18 '13 at 13:49
  • @ᾠῗᵲᄐᶌ thanks, too bad the JSONRequest design proposal doesn't seem to have any traction. –  Jun 18 '13 at 13:56

2 Answers2

0

As I already mentioned in the comments, .getJSON uses the dataType json. By explicitly setting the dataType to jsonp in your .ajax() call, you force jQuery to assume you are going to retrieve a true json with padding-response (which basically means, dynamic scripttag insertion).

Setting the dataType to json will also "fail correctly".

jAndy
  • 231,737
  • 57
  • 305
  • 359
0

IIRC, jQuery doesn't call error on a failed jsonp call (which is what .fail binds to). But, luckily this is a common problem and there is a solution to it: https://github.com/jaubourg/jquery-jsonp

Brad Christie
  • 100,477
  • 16
  • 156
  • 200