I built a query input form with autocomplete in Jquery.
I want to fetch data from an API after the user has selected a value from the input.
Here is the JS on my HTML view. The input form autocomplete on search works fine but on selection, the page returns a 400 BAD Request error. I'm suspecting I have an issue with the way I'm calling the queryData function on select, but I don't know what I'm doing wrong.
<script>
$(function() {
$("#searchBox").autocomplete({
source : function(request, response) {
$.ajax({
type: "POST",
url : "/search",
dataType : "json",
cache: false,
data : {
q : request.term
},
success : function(data) {
var aData=$.map(data, function(item){
return{
label: item.Name + " (" + item.Symbol + ")",
value: item.Symbol
}
});
response(aData);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + " " + errorThrown);
}
});
},
minLength : 2,
select: queryData
});
});
const queryData = async (event, ui) => {
console.log(ui.item.value);
let response = await fetch('http://localhost:5000/getdata?q=' + ui.item.value);
console.log("response", response)
let stockdata = await response.text();
document.querySelector('ul').innerHTML = stockdata;
}
</script>
Here is also the getData route:
@app.route("/getdata", methods=['GET', 'POST'])
def getdata():
term = request.form['q']
finnhub_client = finnhub.Client(api_key="xx")
response = finnhub_client.company_earnings("AAPL", limit=5)
return response