Sunday, 5 February 2012

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

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

Option 1, using PHP: // PHP $html = '<table>' ;     foreach ( $data as $row ) {     $html .= '<tr>...