0

Trying to get the Zendesk API to work

curl https://{subdomain}.zendesk.com/api/v2/tickets.json \
  -d '{"ticket":{"subject":"My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}}' \
  -H "Content-Type: application/json" -v -u {email_address}:{password} -X POST

Works fine, when I convert it to ajax:

var http = "https://SSS.zendesk.com/api/v2/tickets.json";
var data = {"ticket":{"subject":"My printer is on fire!", "comment": { "body": "The smoke is very colorful." }}};


$.ajax({
    url: http,
    beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa("user:pass")); 
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    data: data,
    success: function (data) {
      console.log(JSON.stringify(data));
    },
    error: function(){
      console.log("Cannot get data");
    }
});

I get error:

XMLHttpRequest cannot load https://quran.zendesk.com/api/v2/tickets.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://null.jsbin.com' is therefore not allowed access. The response had HTTP status code 422.

How can I fix this?

Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84

1 Answers1

0

You are falling foul of the Same Origin Policy.

You cannot make AJAX requests in jQuery to third party domains unless using JSONP or CORS (where they are supported - check their documentation for information).

If the URL you are trying to retrieve data from does not support either of those you would need to make a request via your local server, and retrieve the response from that via JS.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Adding special headers can allow cross-domain requests http://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – Boris Zagoruiko Dec 12 '14 at 10:06
  • Okay, I am making a call to Zendesk and they don't accept JSONP anymore, how can I implement CORS? I added `crossDomain:true` – Mohamed El Mahallawy Dec 12 '14 at 10:11
  • @MohamedElMahallawy see Glen's link for information on how to do it, but note the Zendesk API needs to also be setup for CORS. If it is not, then there is nothing you can do. – Rory McCrossan Dec 12 '14 at 10:12