Karachi Gold Rates Today
Daily Gold Rate in Pakistan
Latest gold prices updated automatically
// YOUR GOOGLE APPS SCRIPT WEB APP const API_URL = "https://script.google.com/macros/s/AKfycbx4pPct5caOqzKO1LDQMIEhp8mY06pBWVjnycM6lkKK7soOASvtom1mdElffOAxF-Pg/exec";
// Load gold rates function loadGoldRates() {
const loading = document.getElementById("loading"); const error = document.getElementById("errorMessage"); const ratesContainer = document.getElementById("goldRates"); const updateTime = document.getElementById("updateTime");
loading.style.display = "block"; error.style.display = "none"; ratesContainer.innerHTML = "";
fetch(API_URL + "?t=" + new Date().getTime()) .then(response => {
if (!response.ok) { throw new Error("API request failed"); }
return response.json();
})
.then(data => {
console.log("Gold API Response:", data);
loading.style.display = "none";
displayGoldRates(data);
})
.catch(error => {
console.error("Gold Rate Error:", error);
loading.style.display = "none"; error.style.display = "block";
});
}
// Display rates function displayGoldRates(data) {
const container = document.getElementById("goldRates"); const updateTime = document.getElementById("updateTime");
/* This section supports common API response formats. */
let rates = data;
if (data.data) { rates = data.data; }
if (data.rates) { rates = data.rates; }
/* If your API returns an array */
if (Array.isArray(rates)) {
rates.forEach(item => {
const card = document.createElement("div");
card.className = "gold-card";
card.innerHTML = `
${item.title || item.name || "Gold Rate"}
`;
container.appendChild(card);
});
}
/* If your API returns an object */
else if (typeof rates === "object") {
const keys = Object.keys(rates);
keys.forEach(key => {
const value = rates[key];
if ( typeof value === "string" || typeof value === "number" ) {
const card = document.createElement("div");
card.className = "gold-card";
card.innerHTML = `
${formatTitle(key)}
Today's Rate
${value}
`;
container.appendChild(card);
}
});
}
// Update timestamp updateTime.innerHTML = "Last updated: " + new Date().toLocaleString("en-PK", { dateStyle: "medium", timeStyle: "short" });
// If nothing was displayed if (container.innerHTML === "") {
document.getElementById("errorMessage").style.display = "block";
document.getElementById("errorMessage").innerHTML = "Gold rates were not found in the API response.";
}
}
// Convert API keys into readable titles function formatTitle(text) {
return text .replace(/([A-Z])/g, " $1") .replace(/[_-]/g, " ") .replace(/\b\w/g, letter => letter.toUpperCase());
}
// Load automatically when page opens document.addEventListener("DOMContentLoaded", function() {
loadGoldRates();
});
// Automatically refresh every 30 minutes setInterval(function() {
loadGoldRates();
}, 30 * 60 * 1000);