-1

I'm trying to retrieve the title's categories from JSON data.

For example: https://fr.wikipedia.org/w/api.php?action=query&titles=Albert%20Einstein&prop=categories

I tried something like this:

var requestOnURL = "https://fr.wikipedia.org/w/api.php?format=json&action=query&titles=Albert%20Einstein&prop=categories&callback=?";

$.getJSON(requestOnURL ,function(data) {
  $.each(data.query.pages, function(i, item) {

    alert(item.title);
    //alert(item.categories.title);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If I do an alert for the title it works, but I don't know how to show the categories, still searching.

JJJ
  • 32,902
  • 20
  • 89
  • 102
teddym
  • 55
  • 1
  • 7
  • An article can have multiple categories. You have to loop through the categories array. – JJJ Feb 16 '16 at 09:36

1 Answers1

0

Ok thanks @Juhana i was missing the loop .Working if i do something like this :

$.getJSON(requestOnURL ,function(data) {
        $.each(data.query.pages, function(i, item) {
            $.each(item.categories, function(i, cat){
                alert(cat.title);
            })
        });
    });

Edit : To have only the main categories and not the hidden categories on wikipedia (create a div in your html div class="result-wiki")

//Add clshow=!hidden to the requestOnURL to hide subcategories

var requestOnURL = "https://fr.wikipedia.org/w/api.php?format=json&action=query&titles=Albert%20Einstein&prop=categories&clshow=!hidden&callback=?";

$.getJSON(requestOnURL ,function(data) {
        $.each(data.query.pages, function(i, field) {

            $.each(field.categories, function(i, cat){

                //Add all the result to the div result-wiki
                $('.result-wiki').append("<p>" + cat.title + "</p>");
              
                //Remove the "Category:"
                $('.result-wiki:contains("Catégorie:")').each(function(){
                    $(this).html($(this).html().split("Catégorie:").join(""));
                });
            });
        });
    });
teddym
  • 55
  • 1
  • 7