For context: I have a home page (index.js) which has a search bar. I'm trying to use jQuery's autocomplete function to enable autocomplete on this search bar. This function can take in an array parameter for data.
How do I properly request this data from the server? and How do I properly store this data? I'm looking for an example with concrete syntax to complete this task.
I assume that the server can serve this data when the client first makes a request for the "index" page and then store this data into a variable for later use, but I can't seem to get this to work.
Here is some of my code from index.js:
app.get('/showNames', function (req, res) {
var indexFile = require('./serverJS/page_index.js');
var promise = indexFile.getTitleArray();
promise.then(dataArray => {
console.log(dataArray);
res.send(dataArray);
})
});
The above code logs the correct data to console. However, there seems to be a disconnect with my server side code (index.ejs):
<script>
$(function() {
var dataArray;
fetch('showNames')
.then(data => {
dataArray = data;
console.log(JSON.stringify(dataArray));
})
$( "#searchBox" )
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
dataArray, extractLast( request.term ) ) );
}
})
})
</script>
Of course, the autocomplete has more code, but I think that's all the relevant code to my problem. When I try to print the variable "dataArray" server side, I get {}.
Honestly, I can't even tell if I'm solving this problem the correct way or if I'm going in the right direction anymore.
I'm not sure what is relevant so I'll just list the technologies I'm using. I'm using nodejs with express, ejs as my templating engine, and jsdom to enable jquery on ejs files.