Using Clerk.js to make API Calls

Clerk.js can be used to make more advanced API calls

You can use Clerk.js to make API calls, by using the built in function Clerk.call(), this function takes 3 arguments.

Example Call

Define the function, and call it in the tracking-script.

HTML

<script type="text/javascript">
    (function(w,d){
      var e=d.createElement('script');e.type='text/javascript';e.async=true;
      e.src=(d.location.protocol=='https:'?'https':'http')+'://cdn.clerk.io/clerk.js';
      var s=d.getElementsByTagName('script')[0];s.parentNode.insertBefore(e,s);
      w.__clerk_q=w.__clerk_q||[];w.Clerk=w.Clerk||function(){w.__clerk_q.push(arguments)};
    })(window,document);

    Clerk('config', {
      key: 'INSERT_YOUR_API_KEY_HERE'
    });
  </script>

<script>
  function popularProducts(){
    Clerk("call",
      "recommendations/popular",
      {
        limit: 10,
        labels:["Home Page / Bestsellers"]
      },
      function(response){
        console.log(response);
      },
      function(response){
        console.error(response);
      }
    );
  }
</script>

Response

The response to a JavaScript Object, with the status of the API call, and the result.

JavaScript

__clerk_cb_1(
  {
   "status":"ok",
   "count":72,
   "facets":null,
   "result":[399,410,551,338,403,439,425,402,406,456]
  }
);

Working with the response

Use a Callback function to handle the response

HTML

<script>
  Clerk("call",
    (
      "search/categories",
        {
          'query': "men",
          'limit': "10"
        },
        function(x){
          var cat = x.categories;
          if(cat.length > 0)
          {
            let heading = document.createElement('h3');
            heading.textContent = 'Related Categories';
            document.querySelector('#your-target').append(heading);
          }
          for(var index in cat) {
            var clerkName = cat[index].name;
            var clerkUrl = cat[index].url;
            let link = document.createElement('a');
            link.href = clerkUrl;
            link.textContent = clerkName;
            document.querySelector('#your-target').append(link);
         }
      }
   )
</script>

This example will return the categories matching the query, and present them as text. This way you can make calls to our API quick and easy.