Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax request using jsonp error

I'm writing an app and I need to access some json data in the client side from another server. Because of the cross domain issue I plan on using jsonp. jQuery allows me to do this using the $.getJSON() method, however, I have no way to tell if the method has failed (i.e., the server is not responding or something). So I tried the approach to get the JSON data using $.ajax instead. But it's not working and I don't know what to try. Here an example showing my issue:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
 <html>
 <head>
      <meta http-equiv="Content-type" content="text/html; charset=utf-8">
      <title>TEST</title>
      <script type="text/javascript" src="scripts/jquery-1.5.1.min.js"></script>
      <script type="text/javascript">
           $(document).ready(function() {
        $('#button_detect').click(function(){
            var feedApiAjax = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=';
            var feedApiGetJSON = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=';
            var feedUrl = 'http://www.engadget.com/rss.xml';

            $.ajax({
                url: feedApiAjax + feedUrl,
                datatype: 'jsonp',
                success: function(data) {
                    console.log('$.ajax() success');
                },
                error: function(xhr, testStatus, error) {
                    console.log('$.ajax() error');
                }
            });

            $.getJSON(
                feedApiGetJSON + feedUrl,
                function(data) {
                    console.log('$.getJSON success');
                });
        });
    });
      </script>
 </head>
 <body>
      <div id="button_detect">CLICK ME!!!!</div>
 </body>

If you create a web page with this code and click on the "Click Me" div you'll see that the $.getJSON request is working and the $.Ajax one is not. I've tried putting/removing the "callback=?" tg, used "jsonp" and "json" data types, but non of this worked.

Any idea on what might I be doing wrong?

Cheers!

like image 659
brafales Avatar asked Mar 09 '11 14:03

brafales


1 Answers

When the dataType is jsonp, jquery won't fire the error function automatically. This is described in the documentation under the "error" option:

Note: This handler is not called for cross-domain script and JSONP requests. see here.

The workaround is to explicitly specify a timeout as an option. If the server doesn't respond in the specified amount of time then the error function will be called. More about this here.

like image 200
djp3 Avatar answered Sep 20 '22 15:09

djp3