0

I have below code:

apitest.php

<!DOCTYPE html>
<html>

    <head>
        <title>WEBPAGE</title>
        <link href="main.css" rel="stylesheet" type="text/css" href="" />
        <script type="text/javascript">

            function test(){
                const userAction = async () => {
                const response = await fetch('<some_api_url>');
                const myJson = await response.json(); 
                document.getElementById("demo").innerHTML = myJson
                }
            }
        </script>
    </head>

    <body>
            <button onclick="test()">Click</button>
            <p id="demo"></p>

    </body>

</html>

I am trying to demo call GET api whose response is very basic json data:

{"Status":"OK"}

but I am not getting the above response. Can anyone please help me resolve the issue. Thanks

1 Answer 1

1

Your test function simply defines a function, userAction to make the API request. But this function is never called, so the request is never sent.

Simply add this line:

userAction()

at the end of the test function.

Sign up to request clarification or add additional context in comments.

4 Comments

I have added this line at the end of the test function but nothing seems to be happening. Can you post the code.
Which code? I have nothing else to suggest - calling the function should definitely make something happen. Are there any errors reported on the console?
I have been able to do it but the response I am getting is [object object] instead of {'status': 'ok'}
Right, that's exactly what I expected from your code. You just need to set the innerHTML to response if that's the output you want to see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.