Deeptiman Pattnaik Deeptiman Pattnaik - 9 days ago 5
Javascript Question

Javascript Ajax call not working?

I am trying to make POST request using Ajax call but i am getting error with status code 0 , where as all the request parameters are working in Advanced REST Client.

MyCode:

<button>Post</button>

$('button').click(function(e) {
e.preventDefault();

$.ajax({
url: "https://api.sendgrid.com/v3/mail/send",
type: "POST",
contentType : 'application/json',
headers : {
'Authorization' : 'Bearer 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',
'Content-Type' : 'application/json'
},
data: JSON.stringify({
"personalizations": [{
"to": [{
"email": "test@example.com"
}]
}],
"from": {
"email": "abcd@gmail.com"
},
"subject": "Great, World!",
"content": [{
"type": "text/plain",
"value": "Cool OK!"
}]
}),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status) {
alert("error : "+status+" :: "+JSON.stringify(xhr));
}
});
});


This is my above code , while running it's keep on throwing error saying

{"readyState":0,"responseText":"","status":0,"statusText":"error"}


Also check in jsfiddle

Please help me out , suggest me some solution , i am not able to find the problem in the code.

Answer

Browser extensions aren't as limited to Cross Origin Requests as the browser itself. So an extension like Advance Rest Client or Postman are allowed to request Cross Origin Resources. See this article from Chrome: https://developer.chrome.com/extensions/xhr

So when you create a website that wants to access resources from another domain, you have to enable CORS, just as Matt was saying.