Button onclick js function to make the api call and show results

This commit is contained in:
Joseph Ferano 2023-05-17 20:28:55 +07:00
parent c443640ae7
commit a7415c6393
2 changed files with 22 additions and 1 deletions

View File

@ -10,7 +10,8 @@
<h1>Zip My Link</h1>
<p>Type your long URL into the box and get a shorter URL back!</p>
<input type="text" id="url-input" placeholder="Enter your URL here">
<button onclick="submitUrl()">Shorten Url</button>
<button onclick="shortenUrl()" id="submit-btn">Shorten Url</button>
<p id="result"></p>
<script src="static/main.js"></script>
</body>
</html>

View File

@ -0,0 +1,20 @@
async function shortenUrl() {
const url = document.getElementById("url-input").value;
const btn = document.getElementById("submit-btn").value;
// btn.enab
const response = await fetch("/api/v1/urls", {
method: 'PUT',
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: url, username: "anonymous" })
});
const data = await response.json();
const resultElement = document.getElementById("result");
if (response.ok) {
resultElement.textContent = `Shortened Url: ${data.shortenedUrl}`
resultElement.style.color = "black";
} else {
resultElement.textContent = `Error: ${data.detail}`
resultElement.style.color = "red";
}
}