Ajax detect "Cross-Origin Request Blocked" error - javascript

We are using third party API on our code to get data.
$.ajax({
url: API,
success: function(html, textStatus, xhr){
//IF OKAY
},
error: function(html, textStatus, xhr){
console.log( "!!!!!!!!! ERROR !!!!!!!!!!!!" );
console.log( "----", html );
console.log( "----", xhr.status );
},
});
How can detect on error if the error is
Cross-Origin Request Blocked
Any help would be appreciated.

Unfortunately, it's not possible to definitively access this type of error in browsers for security reasons. Please see this similar thread Is it possible to trap CORS errors?

Related

Unable to handle scenario: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access

I have a form on a webpage which I'm using to capture data and post to a Google Form. The code I've used I saw on this answer. Now, as expected, I'm receiving an error like the following:
XMLHttpRequest cannot load
https://docs.google.com/forms/d/.../formResponse.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
My script making the request is as follows:
function postToGoogle() {
$.ajax({
url: "https://docs.google.com/forms/d/.../formResponse",
data: {"entry.1691469052": "test message"},
type: "POST",
dataType: "xml",
success: function() {
alert("Success");
},
error: function() {
alert("Error");
}
});
}
$(document).ready(function(){
$('#form').submit(function() {
postToGoogle();
return false;
});
});
Now even though I get the error, my data still persists to the form which is the outcome I want.
The issue I'm facing is that in the event that data is passed, I want to display a message to the user saying the data was received. What I'm trying to do is either:
fix the error through using CORS or similar (methods I'm not familiar with and can't find an answer for on SO)
somehow check within my 'error' function that the only issue is the No 'Access-Control-Allow-Origin' one and then produce a 'success' message in that scenario. If there are other issues I'll just throw an 'error' message back to the user
So far I've not been able to find something that works. Any thoughts?
See the $.ajax doc:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest)
object, a string describing the type of error that occurred and an
optional exception object, if one occurred. Possible values for the
second argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error."
So you can write something like:
error: function( jqXHR, textStatus, errorThrown ) {
if( errorThrown.indexOf("Access-Control-Allow-Origin") > 0 ) {
// success...
}
The error text can also be inside jqXHR.responseText.

Calling External API with Javascript

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?
This is what I have so far using jQuery and ajax:
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'json',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
It is throwing a alerts that just says "Status:" and "Error:"
The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."
Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.
If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).
Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN
You can use JQUERY and AjAX. You can send/get information information to/from your API either by post or get method.
It would be something like that:
$("#ButtonForm").click(function(){
$.ajax({
url:(Your url),
dataType:'json',
type: 'post',
data: yourForm.serialize(),
success:function(response){
** If yout API returns something, you're going to proccess the data here.
}
});
});
Ajax:
http://api.jquery.com/jquery.ajax/
You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.
Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.
My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.
When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.
Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'jsonp',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If you use jquery, use .post, or .ajax, to submit
$.post(url, data, callbackSuccess, callbackError);
more about these methods here http://api.jquery.com/jquery.ajax/
example:
var url = 'http://example.com/path/endpoint';
$.post(url, {name: 'Darlan', lastname: 'Mendonça'}, function(response){
// callback success
}, function(response) {
// callback error
});

Error handling cross domain jquery ajax call

I am performing one cross domain get operation as shown below.
$.ajax({
type: "GET",
url: "http://localhost:65249/api/item/get",
data: {
searchText: "test"
},
dataType: "jsonp",
async: false,
success: function (results) {
alert(results);
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status && jqXHR.status == 401) {
alert("Unauthorized request");
} else if (jqXHR.status && jqXHR.status == 404) {
alert("The requested page not found");
}
}
});
But success or error block is not getting called after request is completed. when i debug java script in developer console i am receiving error but error block of javascript is not getting called.
GET http://localhost:65249/api/item/getallproducts?callback=jQuery182028460139059461653_1396510235829&searchText=test&_=1396510674779 401 (Unauthorized)
Unfortunately, if you are using JSONP, all requests that return an error fail silently. This is because JSONP uses a script tag instead of XmlHttpRequest. If you want errors to fire, you need to use XHR with CORS. CORS needs to be configured on the server side, and it works client side only in IE 10+.
error dont work on corss domain calls, see jquery doku. for error:
Note: This handler is not called for cross-domain script and
cross-domain JSONP requests.
Take a look at this answer:
JSONP request error handling

Facebook connector fail gracefully

I'm using the Javascript connector from facebook and I have implemented things as per their instructions and all is well, until facebook is blocked by a corporate policy. Then you get a failure doing this:
ref.parentNode.insertBefore(js, ref);
I added try/catch around it and it still fails.
I have also tried just adding the <script id=... No good.
I have tried it a different way and I can see the problem, I wrote this function :
jQuery.cachedFacebookScript = function(url, options) {
// Allow user to set any option except for dataType, cache, and url
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax({
dataType : "script",
//cache : true,
url : url,
error : function(XMLHttpRequest, textStatus, exception) {
logger("Ajax failure: " + exception);
}});
};
and then added
$.cachedFacebookScript('//connect.facebook.net/en_UK/all.js')
.done(function() {console.log("Done");})
.error(function() {console.log("Error");})
;
None of the callbacks get called so I can't trap the error.
If I remove the dataType : "script", line, both of the error callbacks get called.
So it smells like a JQuery bug to me, so one way round might be to eval() the javascript that I get back in the success callback... but I don't get that far with the above, when I do have access to facebook I get this error:
XMLHttpRequest cannot load http://connect.facebook.net/en_UK/all.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9080' is therefore not allowed access.
Which from other question on here seems to be a server thing... so how does $.getScript() get the javascript? the doco says its a wrapper round $.ajax, so I wrote a new wrapper:
jQuery.myGetScript = function(url, success, error) {
$.ajax({
url: url,
success: function(response) {
eval(response);
success();
},
error: function (response) {
error();
}
});
}
I get the same Origin error.
The JQuery documentation says that as of JQuery 1.5 you can add a fail()... no you can't this does not work:
jQuery.myGetScript = function(url, success, error) {
logger("Calling getScript()");
ret = $.getScript(url)
.done(function( script, textStatus ) {
console.log("Successfully loaded script");
success();
})
.fail(function( jqxhr, settings, exception ) {
console.log("Failed to load script");
error();
});
};
Is there a way to make this fail gracefully, or at least throw something I can trap and handle/ignore?

jQuery form Plugin

I am trying to upload and submit through AJAX a form and I found jQuery.form plugin http://jquery.malsup.com/form/, here is my code :
$("#submitSlide").click(function(){
var options = {
success: function(data) {
console.log(data);
},
error : function( jqXHR , textStatus , errorThrown ){
console.log( ' broked ' , jqXHR , textStatus , errorThrown );
} ,
dataType: 'html',
type: 'POST',
url: 'http://www.slideshare.net/api/1/upload_slideshow'
};
$('#ssuploadform').ajaxSubmit(options);
return false;
});
But I am getting an error like this :
>>[jquery.form] Server abort: Error: Permission denied to access property 'document' (Error)
>>[jquery.form] cannot access response document: Error: Permission denied to access property 'document'
>>[jquery.form] aborting upload... aborted
DO you have any idea how to fix this ?
Thanks, I appreciate any help !
From $.ajax()
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
You cannot make a cross-origin XHR. See How do I send a cross-domain POST request via JavaScript? for ideas.

Categories

Resources