0

I have been struggling to render a data object returned by an API request on an HTML page, however it keeps displaying the string object on the HTML page. Another problem is that I am not able to make use of the data object returned by the API request outside of the API function in Javascript. See the code below:

  • The API request, the console.log(data) outside the API function does not work
  var params = {
    // Request parameters
  };

  $.ajax({
    url:
      "https://failteireland.azure-api.net/opendata-api/v1/attractions?" +
      $.param(params),
    beforeSend: function (xhrObj) {
      // Request headers
      xhrObj.setRequestHeader(
        "Ocp-Apim-Subscription-Key",
        "ef4ed92186214c868a59d97c3b353661"
      );
    },
    type: "GET",
    // Request body
    data: "{body}",
  })
    .done(function (data) {
    
      console.log(data);

      
      document.getElementById("data").innerHTML = data.results;
    })
    .fail(function () {
      alert("error");
    });



});

console.log(data);
  • The HTML Page
<html>
  <head>
    <title>JSSample</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script src="main.js"></script>
  </head>
  <body>
    <div id="data"></div>
  </body>
</html>
shmsr
  • 3,802
  • 2
  • 18
  • 29
Chuck
  • 1
  • 1
  • 1
    Don't ever post real API keys. And don't ask multiple questions in one. – Andreas Aug 04 '20 at 16:58
  • According to its name `data.results` will be a list of "something" -> Use a loop. – Andreas Aug 04 '20 at 16:58
  • [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) – Andreas Aug 04 '20 at 16:59
  • The API response is an array of objects, not HTML. Setting that as innerHTML forces it into a String which gives you `[object Object],[object Object],[object Object],...` –  Aug 04 '20 at 17:02
  • You're welcome :) (link again, in case it'll disappear below: https://jsfiddle.net/khrismuc/d1jragco/) –  Aug 04 '20 at 19:01
  • Thanks again @Chris G, sorry to bother you / waste your time; what if I want to create a search input field in the html page showing a drop down list of the regions where the attractions are located so that a user can select a region to see the cards of attractions located in that region? For example, the first attraction "Adelaide Memorial Church" is located in the region called "Carlow" please would you have a sample code for this? So sorry to bother, I am just so new to this. – Chuck Aug 04 '20 at 19:29
  • I've updated the fiddle accordingly; this shows how to implement a dropdown and use it to filter the results. –  Aug 04 '20 at 20:42
  • @Chris G, You are a legend Chris. I am so grateful for this. You have made my night. Thank you soooo very much. – Chuck Aug 04 '20 at 22:09
  • @Chris G, the dropdown works ok in the fiddle but when i copy code into gitpod and preview in the browser, the list does not show? I have tried to figure out why but no luck. I'm so sorry to be annoying. – Chuck Aug 04 '20 at 22:32
  • Have you checked the browser console for errors? Can you link me to the gitpod so I can take a look? Is the script below the main HTML? –  Aug 04 '20 at 22:49
  • Hi @Chris G, link to the repo url: https://github.com/Tchucks/Stay_Cation_Ireland – Chuck Aug 05 '20 at 12:42
  • You put the code in `main.js`, which is in your `` element. Which means the ` –  Aug 05 '20 at 13:36
  • @Chris G, Many thanks again. I know my cluelessness must have made you laugh. Sorry again for wasting your time. I appreciate your help greatly. I am trying to build a staycation website as a milestone project for diploma in software development which I am currently doing, however I am quite new to Javascript hence why I am so clueless. Hopefully I will improve with time. Thanks Chris. – Chuck Aug 05 '20 at 13:59
  • You're welcome. I wish I didn't have to spend years to learn all that, but I did; we were all beginners once obviously :) –  Aug 05 '20 at 14:05

1 Answers1

0

You need to pass in a callback function to handle the returned data.

function do_request(cb, cb_fail) {
    var params = {};

  $.ajax({
    url:
      "https://failteireland.azure-api.net/opendata-api/v1/attractions?" +
      $.param(params),
    beforeSend: function (xhrObj) {
      // Request headers
      xhrObj.setRequestHeader(
        "Ocp-Apim-Subscription-Key",
        "ef4ed92186214c868a59d97c3b353661"
      );
    },
    type: "GET",
    // Request body
    data: "{body}",
  })
    .done(cb)
    .fail(cb_fail);
}

function cb(data) {
    // you now have access to the data here
    document.getElementById("data").innerHTML = JSON.stringify(data.results)

}

function cb_fail(error) {
    console.log(error)
}

do_request(cb, cb_fail)
user2263572
  • 5,435
  • 5
  • 35
  • 57
  • You have just refactored OP's code but not addresses any of the two issues (outputting the API result, accessing the result of an async operation) –  Aug 04 '20 at 17:03
  • @ChrisG the callback function has access to the api results and correctly handles data from an async operation. – user2263572 Aug 04 '20 at 17:05
  • I'm aware of that; however OP is asking how to access the data *outside the callback*. This is a common beginner's question about async code that doesn't have a good answer, and your answer isn't actually answering it at all, because you are still accessing the data inside the callback; all you have done is move it to an external function. It also sounds like you *have* to do this, which is also wrong. –  Aug 04 '20 at 17:08
  • @ChrisG what does "$.ajax" return? Other than passing in a success/error function, how would you recommend the response be handled? Nothing "has" to be done any way, but there are usually some commonly acceptable implementations. – user2263572 Aug 04 '20 at 17:15
  • Main issue: the response array has to be handled by looping over it and creating list items or divs or whatever based on the elements. And OP's 2nd question about how to make use of the API result outside the `$.ajax` callbacks, (no matter how exactly they're implented, which is completely beside the point but the only thing your answer is dealing with) is answered by this [linked question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Aug 04 '20 at 17:47
  • @ChrisG feel free to use the "Post Your Answer" button if you have a more profound solution. – user2263572 Aug 04 '20 at 17:57
  • The question is sufficiently answered by Andreas's comments #2 and #3; I just commented on your answer why I downvoted it, then proceeded to give a more detailed explanation when you didn't understand my reason. Don't take it personal. –  Aug 04 '20 at 18:01
  • @ChrisG that's what I expected – user2263572 Aug 04 '20 at 18:04
  • Not sure what you mean by that, but here's the code part of my hypothetical answer: https://jsfiddle.net/khrismuc/d1jragco/ –  Aug 04 '20 at 18:25
  • @ChrisG I knew I'd get something useful out of ya. There you go, next time let's try without the 10 extra comments. – user2263572 Aug 04 '20 at 18:28
  • I really do hope you find it useful, especially given [this answer](https://stackoverflow.com/questions/63238903/read-json-file-as-javascript-variable-on-page-load) of yours which, despite the OP over there claiming the opposite for whatever reason, does not solve their problem at all. The other question even contains the actual solution near the bottom, yet you answer with a pointless refactoring of their first snippet. So again, I do hope my fiddle helps clarify things for you. –  Aug 04 '20 at 18:35
  • Again: despite what you may believe, passing a reference to an external function instead of an anonymous one directly does not solve the extremely common "how do I return the response of an async call" beginner's problem. And moving the ajax call into a function only to call it exactly once when the page loads anyway does also solve exactly nothing. –  Aug 04 '20 at 18:38
  • @Chris G, Thanks very much for your answer, that's exactly what I was looking for. I am a beginner indeed. – Chuck Aug 04 '20 at 18:45