ajax CORS error handling - javascript

i have an API which support CORS, but some of them is not support CORS yet. i do the request using ajax/jquery. how do i handle the error if the request is failed due to CORS restriction? eg, pop an alert to notify user that it's failed.
i tried this.
function poster(path, body, callback){
var url = 'http://mysite/';
url += path;
try{
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: JSON.stringify(body),
headers: {'Content-type':'application/json', 'Accept':'application/json'},
success: function(result){
callback(result);
}
});
}catch(e){
callback({'error':'Cross Origin Issue'});
}
}
this doesn't work, my browser (chrome) still throw error to the console. so, how do i handle this, so it will call the callback function instead of throwing error to the console?

Related

Instagram API. XMLHttpRequest cannot load URL. Response for preflight has invalid HTTP status code 405

I'm pretty new on using APIs and I am having a problem with Instagram's new api.
For a dislike function, the documentation states to use a delete method, but I keep getting an error: XMLHttpRequest cannot load URL. Response for preflight has invalid HTTP status code 405.
Funny thing is that when I try the exact same thing with curl, it works.
For example, this is a working method: curl -X DELETE https://api.instagram.com/v1/media/{media-id}/likes?access_token=ACCESS_TOKEN
But if I try to use it with javascript
if( user_has_liked ){
$.ajax({
crossDomain: true,
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'DELETE',
success: function(data){
response = data.data;
document.getElementById(photoId).className = "fa fa-heart-o";
document.getElementById(photoId).onClick = function(){
subscribe(photoId, false);
}
}
});
}
All I get is a 405 error.
I've tried enabling CORS but it seem to work either
I would be really grateful if anybody could give me a hand on this.
Many thanks!
I solved this issue sending a request utilizing the POST method and "delete" like a parameter. Then it is looking like this:
$.ajax({
url: "https://api.instagram.com/v1/media/"+ photoId +"/likes?access_token=" + ACCESS_TOKEN,
method: 'POST',
data: {_method: 'delete'},
success: function(data){
console.log(data);
}
});
Font: http://laravel.io/forum/02-20-2014-sending-a-delete-request-via-ajax

How to get the response text from an AJAX request using jQuery

I am trying to make a JSONP request to a server. This is my code:
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function() {
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});//code indentation
When I run the code it errors. But if I open the developers tools in Chrome (ctrl+shift+I) I can see the request under "network". Clicking on it shows the correct response (and shows the request was accepted).
Apologies is there is a really obvious solution (I have tried searching, but with no luck), but at this point I am well and truly baffled. Any help would be really appreciated.
::EDIT::
changing the error function to:
error: function() {
console.log('error', arguments);
},
returned the message "jsonCallback was not called" Thanks to Aaron Digulla below.
The response from the server is JSON, not JSONP (checked with JSONlint)
When you say "it errors", my guess is that you get alert(2). To find out why, log the function arguments to the console:
...
error: function() {
console.log('error', arguments);
},
...
jQuery will pass additional information (like the error message) to the function. That should help you understand why it fails.
The same is true for the success function which gets the server response, for example.
[EDIT]
I get the error jsonCallback was not called
That means your server isn't returning JSONP. JSONP looks like name({...}) while normal JSON looks like {...}. Please check your server's configuration and make sure it actually supports JSONP and that the response looks correct.
I should have seen this from your code:
dataType: 'jsonp'
headers: {
'Accept': 'application/json', //this is required by the server
}
That means you're sending a JSONP/JSON mix which can't work. If you use a certain dataType, then let jQuery build the correct headers.
The success function has argument and from that argument you can get the response text.
$.ajax({
type: 'GET',
url: myURL,
async: false,
crossDomain: true,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
headers: {
'Accept': 'application/json', //this is required by the server
'key': key
},
success: function(response) {
alert(response);
alert('1');
},
error: function() {
alert('2');
},
complete: function(){
alert('3');
}
});
You cannot set async: false for a jsonp request due to nature of it, adding script tag to handle response method.
dataType: 'jsonp
as you mentioned,the type of data that you're expecting back from the server is jsonp but may be your server will return any other format rather than jsonp.. so check it which type of response your server is returning in under Network in browser console... then if it is not jsonp format, change your respons return type....

JSONP responseText on http error

I am using a jsonp ajax request with jQuery to send some data. When this data could not be processed for some reason, I would like to return the result with a http status other than 200. This way I can use my access logs to parse them for statistics.
Unfortunately, I don't get any response when the status code is not 200, although the jQuery callback is in the response body (when I check with firebug). Is there a way to catch the response?
$.ajax({
type: 'GET',
url: '{{ sendMsgUrl }}',
async: false,
data: { 'form': formData },
dataType: 'jsonp',
success: function(json2) {
if (json2.status == 'ok')
// do stuff
else {
// output error
};
},
error: function(xhr, status, error) {
// this doesn't work: it never gets here
alert(xhr.responseText);
var json2 = eval("("+xhr.responseText+")");
}
}).fail(function(jqXhr) {
// never gets here either
alert('status '+jqXhr.responseJSON);
});
No. JSONP doesn't use XHR. It injects a <script> element into the page.
In theory, you might be able to find an error event handler to that script, but it won't fire for cross-origin requests (and there isn't much point in using JSONP unless you are making a cross-origin request).
You'll never get any details of the HTTP response headers in any event handler when using JSONP.

Jquery not handle HTTP errors when the request gets failed

My problem is "simple". I'm developing a hybrid Android application that makes HTTP requests via Jquery Ajax.
The problem is that when my requests gets failed(Server returns 401/403 ...etc), Jquery fires only HTTP 404 error that is not correct.
I'm making HTTP post requests like that:
var request = $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: obj,
cache: false,
contentType : 'application/json',
beforeSend : function(xhr) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + password));
},
success: function(data){
// Success
},
error: function(request, status, errorThrown){
console.log("call Login ajax failed with error, status:" + status + " errorThrown:" + errorThrown);
console.log("call Login ajax failed with errorCode : " + request.status);
}
The strange thing is that when i run my project as DynamicWeb project in my browser at my PC and in the url use my ip address the jquery fires the correct error events, but when i use "localhost" in the url, the jquery act as in the android devices, fires only 404 event.
I tried to change jquery libary to a newest version 2.1.1 but this doesn't help.
PS. I'm using jquery 2.0.2...
You'll need to set the header of the response to Content-type: application/json.
Before you echo the json. Or you could set the type of the ajax call to text, html.
Also it is recommended to chain your callback functions with jquery like so
$.ajax({
url: url,
headers: { "Accept-Encoding" : "gzip" }, // Use the response seen in sniffer
type: 'POST',
dataType: 'json',//be sure you are receiving a valid json response or you'll get an error
})
.done(function(response) {
console.log("success");
console.log(response);
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
The problem for me was that server doesn't allow Cross-domain requests. So i must set "Access-Control-Allow-Origin:", "*" header in responses from my server and everything will be ok...

PhoneGap - Sending JSON encoding data error

I am using Phonegap to connect to a server to authenticate a user. The server expects the data to be Json encoded, and I will get the response back from the server.
var serviceURL = "http://appdev/PEPS-CS-Services/";
The serviceURL (APPDEV) is hosted on our network within the office.
var loginData = {
'strUniqueID' : '123',
'UserName' : 'User123',
'Password' : 'Password123'
};
I have checked the login credentials and they are fine. When I try the following:
$.ajax({
type: "POST",
url: serviceURL + "services/AuthenticationServices/authenticateUser",
data: loginData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
I get the Access-Control-Allow-Origin error in my console.
XMLHttpRequest cannot load http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
I had a look around, and I was suggested to use Jsonp as the dataType in the ajax request, which does give me back the response I was looking for. However, it isn't alerted out as it should be, the console shows the url with the parameters used in the loginData variable, as below
Resource interpreted as Script but transferred with MIME type application/xml:
http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser?callback=jQuery164017807046906091273_1396515434941&strUniqueID=123&UserName=Mark&Password=Password1&_=1396515434963"
When I open the link in a browser i get the correct response, as below
<ns:authenticateUserResponse xmlns:ns="http://services">
<ns:return>SESSION ID HERE</ns:return>
</ns:authenticateUserResponse>
However, I also get the Uncaught SyntaxError: Unexpected token < error below it.
I have tried to change to data: loginData to data: {'data':$.toJSON(loginData)}, but still the same error.
My questions are the following:
Am I sending the data over correctly? Why does the jQuery164017807046906091273_1396515434941 get added to the URL before the parameters?
And why am I getting the Uncaught SyntaxError too?
Is this because the server is sending back the incorrect format of the data? It is currently sending back XML
Any help would be greatly appreciated, thanks
This is a familiar cross context issue, you are not allowed to request resource from another domain with simple ajax call and expect a result.
Instead, use a jsonp call and regiter a callback function to call when return result:
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
/* show json parsed data */
alert(data);
};
$.ajax({
url: serviceURL + "services/AuthenticationServices/authenticateUser",
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,
data: loginData,
success: success,
error: function(errMsg) {
alert(errMsg);
}
});

Categories