Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

druc's avatar
Level 1

Passing data to view vs fetching with ajax

Hi all,

I'm building a calorie tracker and it involves two lists of food items: one list with foods added by the user, one containing the default food directory (added by me).

I'm having a dilemma whether to pass data directly to view or fetching it using xhr requests.

Given the fact that I can control the default food directory size (let's say 300 items) should I pass the data directly to the view and use JS to allow the user to search the list, or I should go with xhr requests to filter the results?

The downside of using xhr is quite obvious - It's not as snappy as having the data already loaded. But what about passing the data directly? What are the downsides?

Thanks in advance

0 likes
4 replies
arthurvillar's avatar
Level 9

It really depends on the size of your default food list. Here are my opinions on both strategies:

  • use Ajax requests

Ajax requests are incredibly fast and search functionalities with large data usually are populated with ajax requests. If you have a gigantic list of food I would definitely use Ajax and load only what the user searches for. You can easily implement that with tools like typeahead.

  • pass data to view

If you will only have about 300 food items in that list, passing them to the view is not a bad idea as the loading time would not significantly affect your app's performance. It is also easy to sort and filter elements with JS. A tool like list.js would be useful in this case.

Cronix's avatar

You can also use a combination. For 300 items, I'd be using pagination. Page 1 would just load the view with data for page 1. Subsequent pages would use ajax and load data for those pages and update the dom.

1 like
druc's avatar
Level 1

@Ricardo @arthurvillar - the list now has 100 items - I doubt that it will ever go past 300 so I will pass the items directly for now and fallback to ajax if the list gets bigger.

I'm familiar with typeahead, but I haven't heard about list.js - it looks great, so thanks for that!

@Cronix - that would work in most use cases. In my case I don't need pagination as I'm using the items to populate a custom select/dropdown - which will only appear when the user starts typing and will also be limited to something like 7 results or so.

Anyway all, thanks for the second opinion

2 likes

Please or to participate in this conversation.