2

I am trying to work out how to embed an API call response into my index.html file in order to update a website counter using JavaScript.

I have tried multiple blogs and YouTube tutorials but as I'm not experienced with JS I am really struggling.

Here is my API: https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello/

Here is my attempted script.js file:

const countEl = document.getElementById('count');

updateVisitCount();

function updateVisitCount() {
    fetch('https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello/')
    .then(res => res.json())
    .then(res => {
        countEl.innerHTML = res.value;
    })
}

As my API updates automatically each time the page is refreshed, I presume I do not need the JavaScript function itself to count - but I don't know how to rewrite it correctly.

Here is the snippet from my attempted index.html file:

</div>  
  <p>This page was viewed</p>
  <h1 id="count"></h1>
  <p>times</p>

I would like my static webpage to display This page was viewed [return result of API call] times.

Thanks in advance!

--UPDATE--

I have managed to resolve this, thanks for the contributions @Barmar as they steered me in the right direction, and updating the res.value to res.clicks was an essential step.

However, the main issue was the fact that my API is linked to API Gateway and a Lambda function, and I was missing some key code in there. I realised this when trying to enable CORS on the API Gateway resource, and in searching for help I found this SO thread. One of the comments in there had the correct code to include in the Lambda function (I've marked it between >>> <<<):

return {
    'statusCode': 200,
    >>>'headers': {
        "Access-Control-Allow-Origin": "*"
    },<<<
    'body': json.dumps({'clicks': int(ddbResponse['Attributes']['clicks'])})

When I updated that in my Lambda function, and refreshed the website based on my updated index.html file, it worked correctly.

Thanks again everyone!

fhoskyns
  • 51
  • 6
  • Are you getting any errors in the JavaScript console? Like something related to CORS? – Barmar Mar 02 '21 at 21:27
  • Does this answer your question? [Display API request results in HTML page using only js](https://stackoverflow.com/questions/46770892/display-api-request-results-in-html-page-using-only-js) – Auqib Rather Mar 02 '21 at 21:31
  • @Barmar I'm using Codepen and not getting any CORS errors, it's just not displaying the API response – fhoskyns Mar 02 '21 at 21:32
  • @AuqibRather thanks for the suggestion, I can't work out how to apply the JS in that answer to my own use case, as it contains things like ```var price_USD = document.getElementById('price-usd');``` – fhoskyns Mar 02 '21 at 21:35
  • 1
    `res.value` should be `res.clicks` – Barmar Mar 02 '21 at 21:44
  • thanks @Barmar, I will try that too. I'm not sure who voted down my question, but as this is only the second question I've asked, I'd be keen to know where I could do better – fhoskyns Mar 02 '21 at 21:55
  • Is your HTML page also stored on the same AWS server? – Barmar Mar 02 '21 at 21:58
  • Do you actually get the words `[return result of API call]`? – Barmar Mar 02 '21 at 21:59
  • @Barmar yes the HTML page is stored on the same AWS server and no I don't get the words ```[return result of API call]```. I want to get the number of clicks returned from the API call – fhoskyns Mar 02 '21 at 22:01
  • I know what you want to get, I'm trying to understand what you're getting instead. – Barmar Mar 02 '21 at 22:04
  • Did you change `res.value` to `res.clicks`? – Barmar Mar 02 '21 at 22:05
  • Yes I changed it in Codepen, but still get a blank value back – fhoskyns Mar 02 '21 at 22:06
  • Make sure the script is at the end of the HTML. See https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Barmar Mar 02 '21 at 22:06

1 Answers1

0

you have to change code to

fetch('https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello')
.then(response => response.json())
.then(res => {

// do something

document.getElementById("test").innerHTML = res.clicks;   //you used of clicks parameter

//do something

});
<h1 id="test"></h1>
TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • thanks @mohammad soleimanpour. when I try that in Codepen, I get ```This page was viewed [blank] times```. Is that normal? Would I have to actually upload the new index.html file and JavaScript file to see the result? – fhoskyns Mar 02 '21 at 21:52
  • 1
    @fhoskyns Check the console. I get the error `Access to fetch at 'https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.` – Barmar Mar 02 '21 at 21:57
  • @Barmar, which console are you using? I'm not even sure how to check this in a console. Very new to coding – fhoskyns Mar 02 '21 at 21:59
  • 1
    In Chrome use `View -> Developer -> Javascript Console` – Barmar Mar 02 '21 at 22:00
  • @Barmar I see - so you think I should change the CORS settings in AWS? – fhoskyns Mar 02 '21 at 22:03
  • No, you don't need CORS if the HTML and API are in the same domain. – Barmar Mar 02 '21 at 22:03
  • @fhoskyns yes, you have to upload the ńew index.html file, in order to get rid of the CORS error. – TheEagle Mar 02 '21 at 22:11