1

I am writing a little reddit image viewing app, and it works fine if the user enters a valid sub-reddit. But I'm trying to handle the case of a non-existent reddit and can't figure it out.

function load_data(after) {
    $.ajaxSetup({
        "error": function () {
            // this gets called every time, even for a valid sub-reddit
            location.href = 'index.html';
        }
    });

    fetchUrl = 'http://reddit.com/r/' + subreddit + '.json?jsonp=process_images&after=' + after;

    $.ajax({
        type: "GET",
        url: fetchUrl,
        dataType: "jsonp",
        cycleTime: 1,
        success: process_images
        // error: handle_error <- this doesn't work, because we're using jsonp
        // but if I take out jsonp, my whole app doesn't work any longer, since
        // I'm trying to run it as a local .html file, and cross-site scripting
        // security prevents it
    });
}

load_data(after);

This is the response from the server. But I can't handle it in the .ajax method:

GET http://www.reddit.com/r/%3Blk%3Blkl%3B.json?jsonp=process_images&after=&callback=jQuery1510605472848052159_1310668370375&_=1310668370433 404 (Not Found)

Any ideas?

I've tried some of the suggestions on here, like jQuery.getJSON doesn't trigger callback -- but it shows basically the same errors every time, with some random numbers for the 'jQuery##### was not called'.

Community
  • 1
  • 1
Aaron
  • 2,154
  • 5
  • 29
  • 42

4 Answers4

4

Look at this answer to another question.

Essentially it's a limitation in the jsonp implementation in JQuery. The popular answer is to use this js plug-in.

Community
  • 1
  • 1
Christopher Currens
  • 29,917
  • 5
  • 57
  • 77
2

Well actually it's a limitation with cross-domain script injection, which is what jQuery uses for JSONP.

Both the jquery-jsonp plugin and newer versions of jQuery work around this by implementing a timeout. They still can't trap the errors.

A better solution is to use CORS (Cross-Origin Resource Sharing) if possible.

Newer versions of jQuery support CORS but the browser and the remote site must also support it.

Current versions of all major desktop browsers support CORS, Internet Explorer only from version 10.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
1

You can add some headers on server response to allow cross domain if you want...

ChristopheCVB
  • 7,269
  • 1
  • 29
  • 54
0
$.ajax({
  statusCode: {
    404: function() {
      //handle the 404 here
      alert('page not found');
    }
  }
});

here is the ref: http://api.jquery.com/jQuery.ajax/

EDIT

wont work with jsonp see the answer above by ccurrens

Rafay
  • 30,950
  • 5
  • 68
  • 101
  • 1
    that will not work with jsonp as the links provided by ccurrens states that jsonp does not provide error handling therefore there are some workarounds also provided in the answer by ccurrens... – Rafay Jul 14 '11 at 19:22