0

HTML file:

<html>
<body>
<main>
<div class="form-row">
    <div class="form-group col-md-6">
    <input type="email" class="form-control" id="inputEmail">
    </div>
</div>
<button onclick="unsubscribe()" type="button">Unsubscribe</button>
</main>
<script src="js/unsubscribe.js" type="text/javascript"></script>
</body>
</html>

unsubscribe.js content:

function unsubscribe() {
    var email=document.getElementById("inputEmail").value;
    
    var requestOptions = {
        method: 'POST',
        redirect: 'follow'
    };
    fetch("https://apilink/"+email)
        .then(response => response.text())
        .then(result => console.log(result))
        .catch(error => console.log('Error!', error));
}

I'm not sure why the function is returned as undefined when I've defined it in the external js file and linked the js file in the html body.

Amr H
  • 58
  • 1
  • 9
  • 1
    Does this answer your question? [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) – Unmitigated Jul 31 '20 at 19:09
  • Hmmm looks like I have to read up on javascript's asynchronous nature. Thanks! – Amr H Jul 31 '20 at 20:43
  • What do you mean by "*the function is returned as undefined*"? What is the exact error message you are getting? – Bergi Sep 01 '20 at 23:44

1 Answers1

1

Doesn't sound like an async issue if the function is undefined. Sounds like a relative path issue. Try:

<script src="/js/unsubscribe.js"></script>

(notice leading slash, which means find the js file starting from the root).

GAEfan
  • 11,244
  • 2
  • 17
  • 33
  • If that was the reason, a 404 error should be showing up prominently in the console though – Bergi Sep 01 '20 at 23:45