0

I'm doing this thing where I have to call two wikipedia APIs to get the informations I need. I've got my code working, except that I have to click my button twice to get my results.

Can someone see where my sequencing is wrong?

(By the way, all this is new to me so I understand there are probably many many other errors/inefficiencies in my code. Comments are welcome, but not necessary. I plan on cleaning the code as soon as if fix this button thing.)

<script>
    $(document).ready(function () {

        var rXs = [];
        var rX = /^https:\/\/fr.wikipedia.org\/wiki\/(.*)$/;
        var listeURL = "";
        var liste2 = [];
        var rXTitre = [];

        $("#bouton").on("click", function () {

            var quoi = $("#quoi").val();
            $.getJSON('https://fr.wikipedia.org/w/api.php?action=opensearch&search=' + quoi + '&limit=50&format=json', function (json) {
                var liste = json[3];


                for (y = 0; y <  liste.length; y++) {

                        rXs = rX.exec(liste[y])[1];

                        $.getJSON('https://fr.wikipedia.org/w/api.php?action=query&titles=' + rXs + '&prop=langlinks&lllang=en&format=json', function(json2) {

                            for (var pageId in json2.query.pages) {

                                if (json2.query.pages[pageId].langlinks === undefined) {
                                    liste2.push("https://fr.wikipedia.org/wiki/" + json2.query.normalized[0].from);
                                    rXTitre.push(json2.query.normalized[0].to);
                            };
                        };
                    }); 
                };



                for (i = 0;i < liste2.length;i++) {
                        listeURL += "<a href='" + liste2[i] + "' class='btn list-group-item' role='button'>" + rXTitre[i] + "</a>";
                };
                $("#resultats").html(listeURL);

            });
        });
    });
    </script>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
afg
  • 3
  • 6
  • Very related: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – James Thorpe Mar 08 '17 at 15:21
  • Yes. I haven't figured out how to fix my code yet, but this is probably what I need to figure out to do it. Thank you. – afg Mar 08 '17 at 18:30

0 Answers0