This is a design question. I have data that needs to go into an HTML table, which will later be manipulated by the user. Basically the user will be able to select items in the table rows.
I have two options - in both cases I'm using AJAX to get the data:
Create the HTML code using PHP on the server side, send it to the client as HTML. The user then manipulates the table using Javascript (jQuery, essentially).
Send the raw data to the client using JSON, then use jQuery to both create the HTML and later manipulate it by the user.
From a design/ease of coding/beauty point of view, which approach is recommended? Thanks for any insight.
jQuery is a client-side JavaScript library used in web development. jQuery includes several features to make web development easier, such as DOM traversal and manipulation, JSON parsing, visual effects, and more.
PHP is an open-source server-side scripting language with syntax similar to that of C and Perl; for more, see php.net and zend.com .
PHP is a server-side-only language(1), and the fact that PHP scripts can act as clients of other server environments or technologies doesn't mean that it's a client-side language. The client-side term refers to another physical layer away from the server which usually has a graphical user interface.
No. PHP cannot be run in browser.
Why to generate the HTML in PHP:
Why to generate the HTML in jQuery:
So, I'm in favour of the first option, generating the HTML in PHP.
Visual comparison of the two methods, creating a simple table.
// PHP $html = '<table>'; foreach($data as $row) { $html .= '<tr>'; $html .= '<td><a href="#" class="button">Click!</a></td>'; $html .= '<td>'.$row['id'].'</td>'; $html .= '<td>'.$row['name'].'</td>'; $html .= '</tr>'; } $html .= '</table>'; echo $html; ?> // jQuery $('#container').load('handler.php', function() { $('#container a.button').click(function() { // Do something }); });
// PHP echo json_encode($data); // jQuery $.ajax({ url: 'handler.php', dataType: 'json', success: function(data) { var table = $('<table />'); var len = data.length; for(var i = 0; i < len; i++) { var row = $('<tr />'); var a = $('<a />').attr('href', '#').addClass('button'); row.append($('<td />').append(a)); row.append($('<td />').html(data[i].id); row.append($('<td />').html(data[i].name); table.append(row); } table.find('.button').click(function() { // Do something }); $('#container').html(table); } });
From a design / ease of coding / beauty point of view, I'd definitely say go with the PHP approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With