Search code examples
phpajaxgraphfrontend

Best practices when querying backend from script


I'm working on several reports for a web application. I have to show some data from my database in some bar/line charts. I'm using Codeigniter framework so my backend is PHP and my frontend is mostly composed of html and JS. As for displaying graphs I'm using e-charts library.

My question is, what's the best practice when retrieving data for the charts. I could use an ajax call and retrieve general data, then format it in the frontend using JS and finally drawing the chart.

A second option would be to also make an ajax call, but making an endpoint that already sends the data in an specific format that the graph can understand. Then that endpoint would only be used by this specific graph.

A third option is again making a specific function to retrieve and format the data in the backend, but this time work with both the html and the data in the codeigniter view. Then serve the html+js page with all the data required, no asynchronous call involved.

All three options have some limitations, so I'm wondering which is the best practice. And if you have another option I'd like to read about it.


Solution

  • I guess it depends on your needs. Overall, I think the best practice is to make as few dependencies as possible between your backend and your frontend. Especially if you plan to change your frontend or want to serve multiple frontends.

    So the endpoint should return data in a format that can be understood and used by everyone. You need to inject services into the controller of this API. So the controller receives data from the services and responds to it. Just that. The data extraction (from the database) and processing must be done by the services.

    This way you are more flexible. You can create an API controller for your AJAX calls and another controller that renders HTML if needed. With the first one, the API controller, as I said above, the controller receives data and returns it. You let the frontend take care of the computation, transformation, etc. With the second, the controller has to get the data from the injected services but also compute, transform, etc, then render HTML.

    Read about the single-responsability principle or, more generally, the separation of concerns principle.