I’ve been doing a lot of things that include making AJAX requests to get information from the backend of my site when i had an interesting question. Is it better to do the html styling in php, then send to the client, or is it better to send the data as json and then style in javascript?
Since this question is kind of vauge i’ll give an example:
<?php
$data = array();
$data[0] = array("username" => "Supericy", "content" => "just a sample message 1");
$data[1] = array("username" => "Supericy", "content" => "just a sample message 2");
$data[2] = array("username" => "Supericy", "content" => "just a sample message 3");
// etc...
// now this is the choice:
if ($json)
{
return json_encode($data);
}
else
{
// or
$returnString = "";
for (...)
{
$returnString .= '<div class="username">' . $data[i]["username"] . '</div>';
$returnString .= '<div class="content">' . $data[i]["content"] . '</div>';
}
return $returnString;
}
?>
And then in my javascript:
// get the information as raw json
var data = ajax_request(json = true);
var author = document.createElement('div');
author.className = "author";
author.innerHTML = data[i]["username"];
var content = document.createElement('div');
content.className = "content";
content.innerHTML = data[i]["content"];
body.appendChild(author);
body.appendChild(content);
// -- OR --
// get the information as pre-formated html
var data = ajax_request(json = false);
body.innerHTML += data;
As other users have stated, it depends greatly on who your intended audience is. If you are trying to keep startup costs low and are developing for users who generally have a cable / constant internet connection, then you can do whatever floats your boat.
However, if you are designing application and would like it to remain relatively maintainable, you should probably look into JSON. If you do go with JSON, I would also suggest your pick up a javascript library like jQuery so that you can safely and easily handle decoding of the JSON object.
In fact, anymore, even when I am returning HTML from the AJAX page, I still wrap it in a JSON object. It seems a bit more standardized that way and I can easily reuse my previous javascript code.
Here are some basic tradeoffs:
Sending HTML Straight from PHP
Sending JSON to PHP and letting Javascript Convert to HTML
By the way JSON stands for Javascript Object Notation. It follows the standard syntax for objects in javascript:
For example: var blah = {‘variable_name’:’variable_value’};
So my answer to you would be to use JSON, no matter what, but who your viewer is should determine how much data you are sending.