My website features an AJAX call to the Alpha Vantage API, which retrieves JSON data on stock symbols and tickers as users type in the search box.
function handleKeyPress() {
var keywords = document.getElementById("TextBox89").value;
if (keywords.length >= 2) {
var settings = {
"async": true,
"crossDomain": true,
"url": "https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords=" + keywords + "&apikey=B8ARVH4ULKOPMDOT",
"method": "GET"
}
$.ajax(settings).done(function (response) {
var keywordsArray = [];
var json = response["bestMatches"];
for (var i = 0; i < json.length; i++) {
keywordsArray.push(json[i]["1. symbol"] + " - " + json[i]["2. name"]);
}
$("#TextBox89").autocomplete({
source: keywordsArray
});
});
}
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Enter stock symbol/ticker: <input id="TextBox89" onKeyPress="handleKeyPress()" onKeyUp="handleKeyPress()">
In the code snippet above, the stock symbols and company names are retrieved using the jqueryui autocomplete()
method, as demonstrated in this CodePen: https://codepen.io/max-voisard/pen/jOPERRd.
Despite the functionality in the CodePen, the implementation on my website's webpage results in browser freezing and unresponsiveness. This issue, which occurs when interacting with the search box, hints at a problem with the AJAX request's asynchronicity or potential overload on the webpage's resources.
While I acknowledge the security lapse of storing the API key in client-side JavaScript, the nature of the autocomplete()
method makes server-side implementation challenging. Additionally, the API key in use is not sensitive.