Calling Ticket API from script.js within Zendesk Help Centre - CORS issue



Posted Sep 22, 2023

I am attempting to call the v2/tickets.json API endpoint from within the scripts.js file in the help centre theme.  Both the help centre and API are presumably within the Zendesk environment - so I am using basic auth (rather than OAuth).

However, I receive the following error:

Access to XMLHttpRequest at 'https://XXX.zendesk.com/api/v2/tickets.json' from origin 'https://help.XXX.co.uk' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In a sandbox environment, I am able to call the sandbox tickets API fine passing basic auth (email and API token).  Also, calling the live API from Postman works fine.

My code:

$.ajax({
    url: 'https://XXX.zendesk.com/api/v2/tickets.json',
    type: 'post',
    data: JSON.stringify({ticket: postData}),
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Basic " + btoa('EMAILADDRESS/token' + ":" + 'APITOKEN')
    },
    dataType: 'json',
    success: function (data) {
      console.info(data);
    },
    error: function (xhr, status, error) {
      console.info(error);
    }
});

Thanks in advance


0

3

3 comments

Thank you so much for the best platform. I always use this platform for getting help. I am going to share this platform with my friends as well. Thanks again.

0


I'd like to strongly disrecommend storing Auth data in your theme, be it on script.js or other.

If you're interested in showing your end-user's tickets, you could use the Requests API using their own CSRF tokens to authenticate.

An example is available on the Developer Documentation > Making secured API requests from a help center

Additionally, it'll be a good practice to add a caching/throttling mechanism to those calls, as to avoid hitting an API rate limit.

0


Hi Imran Ali

If you're looking for a quick and efficient way to list the tickets of the same help center in which you're writing your code in a script js file, the Zendesk API is the perfect solution for you. By making a GET request to the /api/v2/tickets endpoint, you can easily retrieve a list of tickets in that help center. Once you parse the JSON response, you can display the tickets as desired. 

Please replace the below code with your, it will give a list of tickets on your helpcenter 

$.ajax({
    url: '/api/v2/tickets',
    type: 'GET',
    dataType: 'json',
    success: function (data) {
      console.info(data);
    },
    error: function (xhr, status, error) {
      console.info(error);
    }
});

 

Don't hesitate to let me know if you need any further assistance!

 

Thank You 

Pulkit

Team Diziana

0


Sign in to leave a comment.

Didn't find what you're looking for?

New post