I need some help in this project. I want to be assisted in finding a better way to display the search results. Currently, I am using .append() and the challenge is if I make an API call the results are appended at the end of the current search results.
The behaviour you are seeing is perfectly normal because, as the name of the jQuery suggests,
.append() only adds data to an element—and currently it’s called inside a
.forEach loop that simply tags additional data at the end every loop.
Have you thought about how to work around what you need to do and where?
EDIT: In addition to what @Gh05d said, there are other bugs with the app a well—for example, the search text field isn’t displaying any text for me (Firefox) even though I’m able to perform searches and get the articles that I expect to see.
I tried to fetch an article, but I got this error:
Uncaught TypeError: Cannot read property 'pageids' of undefined at Object.success
You should implement a check, so that your app doesn’t try to read the undefined value. Something like a loading property, which is a boolean.
It should initially be true, but when an article is fetched, be switched to false.
I was gonna suggest
.html(''), but your way’s better/more readable.
I’d also suggest adding a loading message, because it’s really confusing for users when they click something (e.g. a search button) and nothing immediately appears to happen.
You can use the
beforeSend property in the
.ajax() settings to add one. See the relevant jQuery documentation for how to use it.
I tried using .html() but it only displays the last iterated item.
Currently am not sure what I can do to solve that. I got stuck on that there and decided I should get some help. I am going to work through the other bugs, like catching errors.
If you write statements in a for loop, they’ll be executed on each iteration of the loop. If you don’t want that to happen, write them outside the loop.
I actually like your way better. It’s clearer what’s happening and it most likely has better compatibility.