I need an advice on how to write my website.
In my DB I have some data that I want to dynamically load into different frames on my website. Question is: Where do I convert the raw data to HTML-code?
I currently see the following options:
- convert it to HTML in a PHP function and load that via Ajax on my page
- Get the raw data via Ajax and convert it in Javascript to HTML-code
- Write a HTML-Table manually and then insert the data into it via Ajax
All three of those options have their disadvantages – for instance I need to be able to select the table rows with jQuery which I don’t know how to do when the table HTML-code is loaded into the page with Ajax… to write the HTML-table manually would solve that problem, but the table needs to have a variable number of rows.
Are there options that I haven’t thought about yet? Any other advice for me?
It depends, but I would go with 1 or 2 unless the number of rows and columns is constant.
Option 1 has the advantage that generating HTML in PHP can be done more pragmatically than in Javascript, so if you need to make something really quick, or you have a template system in place on the server side already, try option 1. A huge downside of this approach is that you have to trust the server to send ‘sane’ HTML; if you don’t use SSL for the AJAX calls, a simple MITM attack can easily inject exploitable XSS code, and if the server for some reason sends broken HTML, it is hard to detect and probably impossible to recover from.
So normally, I’d prefer option 2. I wouldn’t even bother with HTML at this point, instead, I’d just manipulate the DOM directly, that is:
.text()to add content to the cell.Example code:
This way, you don’t have to worry about HTML encoding (and thus, XSS), because you are injecting DOM nodes directly – the browser won’t do any HTML parsing at all.