I'm having trouble using jQuery.ajax()
to post a gist to Github. The gist is created, and the response is 201 Created
, but the response tab in Firebug is empty and the error callback is hit.
var data = {
"description": "posting gist test",
"public": true,
"files": {
"test.txt": {
"content": "hello gist!"
}
}
}
$.ajax({
url: 'https://api.github.com/gists',
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
.success( function(e) {
console.log(e);
})
.error( function(e) {
console.warn("gist save error", e);
});
Frustratingly, it works fine in jsfiddle: http://jsfiddle.net/vXpCV/
Maybe this is the issue. jsFiddle is getting different response headers:
Access-Control-Allow-Cred... true
Access-Control-Allow-Orig... http://fiddle.jshell.net
Access-Control-Expose-Hea... Link, X-RateLimit-Limit, X-RateLimit-Remaining, X-OAuth-Scopes, X-Accepted-OAuth-Scopes
Connection keep-alive
Content-Length 1093
Content-Type application/json; charset=utf-8
...
Forresto's own answer is totally valid:
Adding my http://local.dev/ to https://github.com/settings/applications seemed to fix it.
...but as long as this answer shows up when one googles for Gist+jQuery, it should have an explaination of what's going on.
Browsers have a security concern called Same Origin Policy. It forbids a web page to communicate with servers other than the one that page was loaded from, so this basically shouldn't work. There's a workaround technique called JSONP but it only works for GET requests while this example has POST.
Then there's this newer technology called Cross-Origin Resource Sharing (CORS). It allows pages opened in modern browsers to communicate with other servers using the good old AJAX.
GitHub API only accepts CORS requests from domains registered as OAuth Applications on GitHub. When jQuery sends a POST request, it sets the Origin
HTTP header equal to the domain of the site it was launched from.
But i should say that for me the snipped worked out even with a jibberish Origin
header. It worked and i don't know why. :)
Adding my http://local.dev/
to https://github.com/settings/applications seemed to fix it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With