Reputation: 515
I'm trying to authenticate to an API, which only allows you to authenticate using a POST with JSON as form data, in the format of
{"username":"myusername","password":"mypassword"}
I've been trying for three days to get this working with jQuery but I'm running into problems because it's cross domain. How can I accomplish this?
Error message:
"NetworkError: 405 Method Not Allowed
My Code:
var username = "myusername";
var password = "mypass"
var authurl = "https://myurl";
$.ajax
({
type: "POST",
url: authurl,
dataType: 'json',
contentType: "application/json",
async: false,
data: {'json':'{"username":"' + username + '", "password":"' + password + '"}'},
success: function (result) {
$('#json').html(result);
}
})
Upvotes: 0
Views: 1842
Reputation: 3290
I had same issues but I use dataType:jsonp
it worked for me.
Here is jQuery Docs for more details
$.ajax
({
type: "POST",
url: authurl,
dataType: 'jsonp',
context: document.body,
async: false,
data: {'json':'{"username":"' + username + '", "password":"' + password + '"}'},
success: function (result) {
$('#json').html(result);
}
})
Upvotes: 1
Reputation: 318302
It is generally not possible to do an asynchronous POST request to another domain, due to the same origin policy .
JSONP only works because you're allowed to insert <script>
tags into the DOM, and they can point anywhere and do not use XMLHttpRequest (ajax).
If the API you are trying to use supports JSONP that would be an option, otherwise you probably have to look into a solution using PHP to post the data with something like Curl, and then using Ajax to call that PHP script on your own server etc.
Upvotes: 0