37

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:

  1. 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).

  2. 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.

Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
Sleepster
  • 1,150
  • 1
  • 17
  • 24

5 Answers5

37

Why to generate the HTML in PHP:

  • JavaScript should define the behaviour, not the content.
  • Creating in JavaScript requires more markup (multi-line strings aren't as easy as in PHP).
  • It's harder to maintain if your HTML is generated in several places (PHP & JS).
  • You could use jQuery's DOM manipulation functions to create your HTML, but you're shooting yourself in the leg on the long run.
  • It's faster to create the HTML at the server than on the browser (in computational sense).
  • Looping is easier with PHP – it's easy to generate table markup.
  • You retain some kind of combatibility if the user has JavaScript disabled if you output the markup on page load.

Why to generate the HTML in jQuery:

  • You'd save some bandwidth.
  • Binding events might be simpler.

So, I'm in favour of the first option, generating the HTML in PHP.


Visual comparison of the two methods, creating a simple table.  

Option 1, using PHP:

// 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
    });
});

 

Option 2, using jQuery:

// 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.

Community
  • 1
  • 1
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
  • Some good points, but do you think it is really computationally faster for one server to do the work vs thousands of individual clients? – user113716 Feb 21 '10 at 22:27
  • 1
    @patrick, I was talking about the computational speed of one individual page load - the content will load faster if the HTML is created on the server. But of course it is always easier for the server if maximum amount of computations is transferred to the client. – Tatu Ulmanen Feb 21 '10 at 22:49
  • 1
    Hmmm. If you want a comparison on equal grounds (and speed), you should build a string array in the javascript as well and just push the elements. At the end, join them and assign at once. – Andras Vass Feb 22 '10 at 00:58
  • +1 I totally second this. We are putting enough load on the clients' machines as it is with all the tons of JavaScript stuff that is common these days. – Pekka Feb 22 '10 at 22:21
  • +1 for completeness of answer, but I'd remove the point that says "faster on server" as this is not really a point to consider here. You said it yourself it's better to, regardless of option, throw computations to the client. – cregox Apr 12 '10 at 16:44
  • Actually, if you consider this is not client-specific computational data, it could all be cached by the server. That is a lot more optimized in a broader view of computational usage than if every client have to compute the same data every time the page is loaded. So, in a second thought, that's actually a very good point, but if described this way. – cregox Apr 12 '10 at 16:51
  • Just mentioning that in 2017, YouTube started building its entire layout via JS (the page gets all content as JSON). – Firsh - justifiedgrid.com Sep 20 '17 at 16:09
2

If the HTML generated is identical to page HTML you may be able to leverage your existing templating code to generate the same HTML with less code duplication.

Otherwise, JSON is typically more common as it tends to be more compact and it allows you to create nodes and assign non-HTML properties like event handlers to them as you go.

If you create your new nodes by creating an HTML string, however, you have to use HTML-encoding to ensure any <, & or quotes are escaped correctly. There's no built-in function to do this in JavaScript like htmlspecialchars in PHP; it's pretty trivial to write one, but no-one seems to bother. The result is jQuery apps that are full of client-side cross-site-scripting security holes, just as we were starting to make some progress of fixing the server-side XSS stuff.

bobince
  • 528,062
  • 107
  • 651
  • 834
1

Equally compelling arguments could probably be made for both, but you'll likely be sending less data down the pipe if you go with 2.

brian
  • 1,080
  • 9
  • 7
1

I really like the idea of putting things like this together on the client side. I found JavaScriptMVC to be a good Framework (the 2.0 Version is based on jQuery) for that because it has client side view templates (though not everybody likes that approach).

With jQuery alone I find it quite complex to create client side views though (because that is not what it is meant for), so you might be better of with putting everything together on the server side in PHP if you can keep your application equally dynamic that way.

Daff
  • 43,734
  • 9
  • 106
  • 120
0

Both options have plus and negative points, however andras makes a good point in stating whether the content needs to be indexed/searchable. I personally would opt for option 1 thhough as I believe the architecture would be easier to produce.

RichW
  • 469
  • 5
  • 16