Saturday, 29 July 2017

jquery - $.ajax error function is not working




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.


Answer



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!');
});


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...