Reputation: 2677
I am trying to call an API with the help of ajax.
$.ajax({
url:url,
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
async: false,
success: function(data, statusText, xhr) {
console.log("Calling success");
console.log(arguments);
console.log(data.status);
},
complete: function(data, statusText, xhr) {
console.log("Calling Complete");
console.log(arguments);
console.log(data.status);
},
error: function(data, statusText, xhr) {
console.log("Calling error");
console.log(arguments);
console.log(data.status);
}
});
After calling the ajax this is the response in firefox:
You can see in the picture, I am getting 200 statuscode
and in the response, I am getting my JSON data.
Below is the snap of console, after calling ajax.
below is the error object:
Object { readyState: 0, getResponseHeader: .ajax/v.getResponseHeader(), getAllResponseHeaders: .ajax/v.getAllResponseHeaders(), setRequestHeader: .ajax/v.setRequestHeader(), overrideMimeType: .ajax/v.overrideMimeType(), statusCode: .ajax/v.statusCode(), abort: .ajax/v.abort(), state: .Deferred/d.state(), always: .Deferred/d.always(), then: .Deferred/d.then(), 11 more… }
Error I found after digging into the object :
Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'url I passed in ajax'. at Object.send (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:4:14955) at Function.ajax (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:4:10579) at HTMLButtonElement.<anonymous> (http://mywebsitestatic.s3-website-us-west-2.amazonaws.com/:258:4) at HTMLButtonElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:3:6404) at HTMLButtonElement.r.handle (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js:3:3179)
Any Idea what is the error all about.
I have tried to refer many questions from the stackoverflow.com but No one matches with my scenario. Can anybody please let me know where I am going wrong?
Upvotes: 2
Views: 1335
Reputation: 12022
This was a Cross Origin Resource Sharing (CORS)
issue. To fix it, you had to add the below 2 response headers in the server if you can:
setHeader("Access-Control-Allow-Origin:", "origin url of your site");
setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
To confirm this is CORS
issue, you can by pass this security check in chrome
by opening this from the console as below and give a try of the url,
Windows:
chrome.exe --allow-file-access-from-files
chrome.exe --allow-file-access-from-files --disable-web-security
Mac:
open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files
Note: The fix is by setting the above response headers in the server which you are trying to access from the JQuery POST
request.
AWS Link to enable CORS:
http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
References: (To understand more about CORS
)
Upvotes: 1