10

I'm working on some existing code. I have the following code:

$.ajax({
        type: "get",
        url: url ,
        dataType: "jsonp",
        cache: "false",
        jsonpCallback: "onJSONPLoad",
        success: function(json){
               alert('hi!');
               //perform operation
        },
        error: function() {
          alert('Error occurs!');
       }
});

Now when I'm passing valid url it works fine. But when I'm passing invalid url it should through an error alert. But the script is not throwing any error alert. Basically I want validate the url parameter or it is failing? Please help me to find-out the error in my code or suggest me else way to achieve. I have checked the following links but not able to solve my problem:

jQuery Ajax error handling, show custom exception messages
jQuery ajax error function, Ajax Success and Error function failure

UPDATE: I have added below code to log the jquery console log.

  @Override
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Log.d("web chrome client", cm.message() + " -- From line "
                + cm.lineNumber() + " of "
                + cm.sourceId() );
                return true;
            }

Identified the following error: XMLHttpRequest cannot load file:///android_asset/xxxx/new_source.json?callback=onJSONPLoad. Origin null is not allowed by Access-Control-Allow-Origin. -- From line 1 of null

Adding the following code, app is running successfully.

if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
  webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
}

So, basically this is happening as the url is not accessible by the jquery.
Thanks every body for helping me.

Community
  • 1
  • 1
Pradip
  • 3,189
  • 3
  • 22
  • 27
  • get and Paste error from console.. – Naresh Sep 25 '13 at 06:07
  • Your Answer is Here : [First][1] And Here : [Second][2] [1]: http://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages [2]: http://stackoverflow.com/questions/3642348/jquery-ajax-error-callback – Amin AmiriDarban Sep 25 '13 at 06:10

4 Answers4

18

used this

1)replace this: dataType: jsonp for cross-domain request, that means request to different domain and

dataType: json for same domain-same origin request. dataType: "json"

2)You are missing ',' after success function

$.ajax({
        type: "get",
        url: url ,
        dataType: "json",
        cache: "false",
        jsonpCallback: "onJSONPLoad",
        success: function(json){
               alert('hi!');
               //perform operation
        },
        error: function() {
          alert('Error occurs!');
       }
});

3) try this

error: function(jqXHR, exception) {
            if (jqXHR.status === 0) {
                alert('Not connect.\n Verify Network.');
            } else if (jqXHR.status == 404) {
                alert('Requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert('Time out error.');
            } else if (exception === 'abort') {
                alert('Ajax request aborted.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }

4) check this jQuery.ajax

The json type parses the fetched data file as a JavaScript object and returns the constructed object as the result data. To do so, it uses jQuery.parseJSON() when the browser supports it; otherwise it uses a Function constructor. Malformed JSON data will throw a parse error (see json.org for more information). JSON data is convenient for communicating structured data in a way that is concise and easy for JavaScript to parse. If the fetched data file exists on a remote server, specify the jsonp type instead.

The jsonp type appends a query string parameter of callback=? to the URL. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than callback with the jsonp option to $.ajax().

Note: JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. More information about it can be found in the original post detailing its use.

When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.

but you need to fire then code :

var req = $.ajax({
    url : url,
    dataType : "jsonp",
    timeout : 10000
});

req.success(function() {
    console.log('Yes! Success!');
});

req.error(function() {
    console.log('Oh noes!');
});
Shakti Patel
  • 3,762
  • 4
  • 22
  • 29
  • Thanks, for trying `dataType: "jsonp"` is ok. problem is why error block not working. – Pradip Sep 25 '13 at 06:09
  • If I use `dataType: "json"`, error block works. but for valid url succes function is not working as the data return form the url is a dataType of `jsonp`. – Pradip Sep 25 '13 at 06:16
  • 1
    When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired. for this check my updated answer – Shakti Patel Sep 25 '13 at 06:25
  • If this is the reason, have you any idea how to deal with my situation. Please suggest. – Pradip Sep 25 '13 at 06:27
  • can you please check this http://www.haykranen.nl/2011/02/25/jquery-1-5-and-jsonp-requests/ – Shakti Patel Sep 25 '13 at 06:57
  • Thank's for your help. Info provided by you really need full to me. I have update the way how I solved the problem. – Pradip Sep 25 '13 at 12:57
  • Adding the `timeout` seemed to start calling `error` for me when url was invalid. – Moishe Lipsker Oct 16 '15 at 00:51
1

You are missing comma after success function and also change dataType to json

$.ajax({
        type: "get",
        url: url ,
        dataType: "json",
        cache: "false",
        jsonpCallback: "onJSONPLoad",
        success: function(json){
               alert('hi!');
               //perform operation
        },
        error: function() {
          alert('Error occurs!');
       }
});
Swapnil Patil
  • 971
  • 2
  • 18
  • 41
1

A bug recently introduced in chrome 52 (august 2016) can also cause this kind of behavior. Hoppefully, it will not last long.

https://bugs.chromium.org/p/chromium/issues/detail?id=633696

It is not strictly related to the initial problem because it triggers only for GET request started from the onSuccess handler, but I mention it for others who may search help on this problem.

0

Try with this.

     $.ajax({
                type: "get",
                url: url ,
                dataType: "jsonp",
                cache: "false",
                jsonpCallback: "onJSONPLoad",
                success: function(result){
                       alert('hi!');
                       //perform operation
                },    
               error: function( req, status, err ) {
                 console.log( 'something went wrong', status, err );
                 alert('something went wrong'+ status + err); 
               } 
      });

Also read this. http://api.jquery.com/jQuery.getJSON/#entry-examples

and try $.getJSON() instead of $.ajax()

Naresh
  • 2,761
  • 10
  • 45
  • 78