I built a simple JavaScript project based on an idea I had. It uses the fetch function to retrieve data from a database and calculates the price of gold based on user input and dates. The application displays the rate, fetches Kuwait rates, and converts the total cost into Indian Rupees, including any charges, without focusing on complex styling.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="number" id="userInput" placeholder="Enter grams" min="0" step="any">
<input type="date" id="userinput" placeholder="Enter date">
<button type="button" onclick="goldrate()">Submit</button>
<div id="result"></div>
<script>
const myHeaders = new Headers();
myHeaders.append("x-api-key", "sk_A0e2b5a37753268979996D8047862849FAd15A0D6E0A5273");
const requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow"
};
function goldrate() {
const grams = Number(document.getElementById("userInput").value);
const resultElement = document.getElementById("result");
if (!Number.isFinite(grams) || grams <= 0) {
resultElement.innerText = "Enter a gram amount greater than zero.";
return;
}
fetch("https://gold.g.apised.com/v1/latest?metals=XAU,XAG,XPT,XPD&base_currency=KWD¤cies=EUR,KWD,GBP,USD,INR&weight_unit=gram", requestOptions)
.then((response) => {
if (!response.ok) {
throw new Error(`Gold rate request failed: ${response.status}`);
}
return response.json();
})
.then((data) => {
const inrPerGram = Number(data.data.currency_rates.INR);
if (!Number.isFinite(inrPerGram)) {
throw new Error("INR gold rate was not returned by the API.");
}
const formatter = new Intl.NumberFormat("en-IN", {
style: "currency",
currency: "INR"
});
resultElement.innerText =
`Gold rate: ${formatter.format(inrPerGram)} per gram. ` +
`${grams} g total: ${formatter.format(inrPerGram * grams)}.`;
})
.catch((error) => {
resultElement.innerText = "Unable to load the INR gold rate. Please try again.";
console.error(error);
});
}
</script>
</body>
</html>

Top comments (0)