Skip to main content
  1. About
  2. For Teams
Asked
Viewed 1k times
5

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
...
0

2 Answers 2

6

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. :)

Sign up to request clarification or add additional context in comments.

Comments

2

Adding my http://local.dev/ to https://github.com/settings/applications seemed to fix it.

1 Comment

not sure where one can add the URL. perhaps the UI changed since you provided this answer in 2012?

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.