0

I need to make an AJAX request to API to get the word for a hangman game. Also struggling, on reading the word length and displaying it with placeholders. I referenced this link enter link description here , but am still stuck.

//function to get the word from the API using AJAX
  jQuery.extend({
getValues: function(url) {
    var result = null;
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'xml',
        async: false,
        success: function(data) {
            result = data;
        }
    });
   return result;
}
});

//accessing global variable (word)
var results = $.getValues("https://hangman-api.lively.software");
  for (var i < 0; i < word.length; i++) {
    results[i] = "_";
  }
  • Okay what are you stuck on? What isnt working? – Isaac Vidrine Oct 16 '19 at 18:43
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andrew Lohr Oct 16 '19 at 18:44
  • @Rachel Willows take a look at the link above to get some context of async calls, you can wrap your for loop in a function, then call that function from the success handler of the ajax call and pass the result. Also I would suggest to never use `async:false` since it is blocking and can hurt your user experience by slowing down your game. Also unless there is some other context of your game, it seems unnecessary to extend jquery with the getValues function. Just use the ajax call by itself. – Andrew Lohr Oct 16 '19 at 18:46

1 Answers1

1

Hopefully my snippet can help you in some ways. have a nice day!

$(function(){
    $.ajax({
        url: "https://hangman-api.lively.software/",
        type: 'get',
        success: function(data) {
          //how to access word
          console.log(data.word)

          //how to create placeholders
          placeHolder = " _ ";
          placeHolders = placeHolder.repeat(data.word.length)

          //how to print place holder
          $(".placeHolder").text(placeHolders)
        }
    });

})
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  Placeholders : <span class="placeHolder"></span>
</body>
</html>
hifebriansyah
  • 341
  • 1
  • 6