Search code examples
javascriptjqueryjsonzendesk-api

How to link a JSON generated list to display the content of a different JSON file


I'm calling a JSON file (sections.json), and then accessing the array sections, looping through every item and appending the name value to a li. I wish to give this li a link (or click event) to display the articles names of the corresponding section on .sectionArticles. To access the articles of a specific section, I have to access a different JSON file (sections/{section id}/articles.json). I'm clueless on this last part... could someone point me out in the right direction?

Here is my current code so far:

$(function() {

  // URLs
  var  zendeskUrl = 'https://myhelpcenter.zendesk.com/'
  var sectionsUrl = zendeskUrl+'api/v2/help_center/pt-br/sections.json';
  var articlesUrl = zendeskUrl+'api/v2/help_center/pt-br/articles.json?per_page=100';

  $.ajax({
    type: 'GET',
    url: sectionsUrl,
    success: function(data) {
      data.sections.forEach(function(section) {
        $('.sectionsList').append('<li class="sectionName">' + section.name + '</li>');
      })
    },
    error: function() {
      console.log("Error: sectionsUrl");
    }
  })

  $.ajax({
    type: 'GET',
    url: articlesUrl,
    success: function(data) {
      data.articles.forEach(function(article) {
        if (article.promoted == true) {
          $('.promotedList').append('<li class="promotedName">' + article.name + '</li>');
        }
      })
    },
    error: function() {
      console.log("Error: articlesUrl");
    }
  })

})

JSOM Sample:

List ALL Sections: /api/v2/help_center/sections.json

{
   "sections": [
    {
      "id": 115001417087,
      "url": "/api/v2/help_center/sections/115001417087.json",
      "html_url": "/hc/sections/115001417087",
      "category_id": 115000835587,
      "position": 0,
      "sorting": "manual",
      "created_at": "2017-03-22T14:29:48Z",
      "updated_at": "2017-06-13T20:01:01Z",
      "name": "Section 1",
      "description": "",
      "locale": "",
      "source_locale": "",
      "outdated": false
    }
  ],
  "page": 1,
  "previous_page": null,
  "next_page": null,
  "per_page": 30,
  "page_count": 1,
  "count": 8,
  "sort_by": "position",
  "sort_order": "asc"
}

List ALL Articles from Section {id}: /api/v2/help_center/sections/{id}/articles.json */

{
  "count": 9,
  "next_page": null,
  "page": 1,
  "page_count": 1,
  "per_page": 30,
  "previous_page": null,
  "articles": [
    {
      "id": 115008623727,
      "url": "/api/v2/help_center/articles/115008623727.json",
      "html_url": "/hc/articles/115008623727",
      "author_id": 20423232608,
      "comments_disabled": true,
      "draft": false,
      "promoted": false,
      "position": 0,
      "vote_sum": 0,
      "vote_count": 0,
      "section_id": 115001417087,
      "created_at": "2017-06-13T19:46:17Z",
      "updated_at": "2017-06-13T19:59:28Z",
      "name": "Some name",
      "title": "Some title",
      "body": "Some HTML",
      "source_locale": "",
      "locale": "",
      "outdated": false,
      "outdated_locales": [],
      "label_names": []
    }
  ],
  "sort_by": "position",
  "sort_order": "asc"
}

Solution

  • I don't know if I understood the question the right way, but I assume you load the section list in the beginning and then want to load articles only when requested.

    Therefore I'd first store the section id in the section list, so I can reuse it later on.

    $.ajax({
        type: 'GET',
        url: sectionsUrl,
        success: function(data) {
          data.sections.forEach(function(section) {
            $('.sectionsList').append('<li class="sectionName" data-section-id="' + section.id + '">' + section.name + '</li>'); 
          })
        },
        error: function() {
          console.log("Error: sectionsUrl");
        }
      })
    

    With .on('click'), you already went into the right direction but since the sections are generated after event binding took place, you need event delegation to react on your click. you can read more on this here: https://learn.jquery.com/events/event-delegation/

    Additionally, I added the empty() call to clear the article list. If there are previous results, you can move that line into the ajax success function. If you want to keep the old list as long as no valid response has been returned, in terms of usability, I wouldn't. Keeping it doesn't show the user that something is happening. They might wait a moment and click again and again and again and so on. Better rework the error function to show something in the list instead of the console.log.

    $(".sectionsList").on("click", ".sectionName", function(){
      clickedSectionId = $(this).data("sectionId");
      $('.promotedList').empty(); //clear list of previous results
    
      articlesUrl = zendeskUrl + 'api/v2/help_center/' + clickedSectionId + '/articles.json?per_page=100';
    
      $.ajax({
        type: 'GET',
        url: articlesUrl,
        success: function(data) {
          data.articles.forEach(function(article) {
            if (article.promoted == true) {
              $('.promotedList').append('<li class="promotedName">' +   article.name + '</li>');
            }
          })
        },
        error: function() {
          console.log("Error: articlesUrl");
        }
      });
    });
    

    I assume that your ajax calls are setup the way you need them. Just focus on storing the section id and binding the click function the correct way.