I have a templating engine for dynamic page and table rows generation.
The idea is like most templating techniques, that is to prepare an HTML template (visually designing it) and use {{variable_name}} in the HTML block and do a search/replace routine.
At the moment, what i'm doing (and have work flawlessly for months) is that JS sends the HTML template block (say the dynamic/loopable row in a data table (the whole html code) to PHP where it is treated as a template string.. and PHP loops through the results of the SQL query and doing a preg_replace on the template string.
$html_content .= doTemplate("name,address,age",$template_string);
That $html_content is then outputted as a JSON object back to the client browser ..
I know i'm moving more bytes than necessary to and from the backend since my output contains HTML code instead of just the data, but i figured this is a small tradeoff since PHP processing the template replacement is faster than client browser (JS).
This time, I am thinking of doing the templating/string replacements in JS, but im wondering how much slower JS really is doing string.replace routines.
Is it really that much slower?
Related
I was just curious about the title because I have been using PHP to load up my search results with HTML, and now I have started to use javascript for this purpose.
Previously I was doing the following on my website to load search results on a page
<?php
//example code
echo ' <div class = "container">
<div class = "box"> <p> Searh result e.g foo bar </p> </div>
</div>'
?>
Now the above would work when I called an ajax function to post the search text to the PHP page, and the page would return all the matched results along with HTML, and the jQuery would push the result on my page
What I am doing right now is I am posting the search text via ajax to a PHP page but this time instead of returning all the search results packed in HTML tags, it return a JSON type array with only data in it
Now when I receive this data array from PHP I send it to a custom (self-made) javascript function that iterates through the array and generates the HTML as following (e.g.)
for (myData in data)
{
results+='<li>'+
'<div class="row">'+
'<div class="col-xs-12 col-sm-9 no-margin">'+
''+data[myData].name+''+
'<div class="price">'+
'<div class="">'+data[myData].price+'</div>'+
'</div>'+
'</div>'+
'</li>';
}
In the end, the variable results has all the HTML along with data which is then pushed to the page via jQuery append.
So in the first method all the work is being done on the server side and it is returning a huge amount of data because of the HTML tags which will be multiplied by the number of results returned
While in the second method the server will only return a JSON type array of data
and the rest of work will be done on the client side. So The question is, Is the second method better than the first one in any way or not?
Thanks in advance
Both approaches are equally valid, but there are a couple things to consider for each approach:
PHP
It works even if the user has JavaScript disabled
JavaScript
Processing is offloaded to the client, putting less load on your servers.
The actual amount of load is going to be negligible since the only "processing" is building HTML
Less traffic, but if your server is compressing the response (it likely is), then this isn't really a noticeable difference.
Faster, more responsive page if you're using ajax, since it doesn't have to reload the entire page.
Doesn't work if the user has JavaScript disabled.
In the end, I'd go with JavaScript unless you know you have a lot of users who disable it.
Ideally you would have a no-JS fallback where PHP creates the HTML.
When you're talking about small simple website, do what you like...
When it comes to more complex applications you must to separate your data from presentation. So the right way, I think, will be to use templates at first.
Then, you can choose the side:
Client side will be better, when using some framework or your application HTML changes instantly. You get the data you need and render it on client. Using template engine.
Server side may be good if you need to build large amount of HTML with some difficult logic and need it once or twice...
Also you can use the same template engine for both sides, so you can combine.
I think, it's always about the combination of ways, so prepare your app for both.
(Maybe designing from the start for REST)
P.S. It may help: Sharing Templates Between PHP and JavaScript
Not an actual answer... but they're both pretty bad :-/ Why not look at something like Knockout.js. You could just update your view model with the "json type array with only data in it" and you're view updates as if like magic ;-)
Just sayin!
I'm working on a project where it has a number of pages. Each page displays 10 rows where the layout that is using for each page is different. Until now I had the html code of each row in a javascript code and based on the page's url I was using the appropriate html code (if statement). The if statement is inside into a loop which is looping based on the number of rows. The results of the rows are coming from an ajax method. Now I want somehow to separate it so it can be more easily for me to maintain it, basically to remove the html code from the javascript and keep each row's html code into a different file.
Note: the Ajax is in a given time, is sending automatically requests to the php file for any new rows.
One solution which I came out is that I can use the php to create a variable with the html code .
Second solution is to create an array of each record with the html code and then pass it to jquery to print it.
Both solutions I don't know if are good solutions and can help me to maintain the project in the future.
You might consider a template library such as handlebars to help with templating. Frameworks such as AngularJS and Ember also excel at solving these kinds of problems.
Your Web Services API should be returning JSON though, not HTML fragments. Let the client build the DOM, and let the server focus on data.
You should return structured data (see JSON for example) to your AJAX request. This way, you can support multiple interfaces (e.g., a website, an application): each interface will get only the data, and will handle the rendering as it needs.
In your example, you ask for data via an AJAX request, your server responds with a JSON-structured response. JQuery reads it and converts it to javascript array thanks to jQuery.getJSON. With your array, you loop through each element and insert html elements into the webpage.
You have two options:
If your HTML templates is not changing frequently, the best way is to define html templates in your HTML structure using some java script template library (eg. Handlebars) and fill it with data from your AJAX (JSON) requests.
If your HTML templates change frequently or depends on some conditions (data) in row, you should create PHP partial views which generate proper html structure already filled with data.
For many rows it is better idea to create whole table server side to reduce requests.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to create a website for a friend of mine using PHP. It is basically an online store.
I want to use new features of HTML5, CSS3, jQuery and other JS libraries.And I want to keep all the document generation and manipulation separate from PHP.
I have done a lot of searching on Google. People come up with MVC architecture. And that's all good.But the problem is in all the examples or tutorials that I found; people retrieve the data from the SQL based databases, and then echo or print it to generate html, or use some ORM classes to display it. I don't know much about ORM or PHP frameworks.
I have always made pet projects, small websites, nothing like this medium-sized Store.
The way I understand the MVC architecture is this:
**Model:** Basic purpose is to save and retrieve data from the databases.
**Controller:** Do some operations on the data to either store them using Model, or do some operations on the retrieved data (again using the Model), to be passed to the View.
**View:** This is used to display the user the content.
What I want to do is do almost ZERO html generation using PHP.Instead I was thinking of a approach in which :Model is used for database handling only. Controller is used to convert that data into JSON objects, and make those JSON objects available to the appropriate Views.Then using JavaScript I will do the DOM Manipulations according to the JSON objects.
Is this approach any good ? If yes how to do it (especially the part of converting the data retrieved from database to JSON objects).
If you can provide me with a better approach where I won't have to do generate html using PHP, and use PHP for front-end as less as possible.
I am doing all the front-end stuff which the user is gonna see. My friend will be doing all the database handling. I don't wanna get involved in the PHP part, and if it is mandatory (i.e. there is no way-out) then as little as possible.
Please provide me with some solution. In desperate need here.
EDIT: I am especially talking about echo and print commands. I would like to have a fresh slate to work on instead of getting the html creation mixed with PHP and JavaScript.
If NOT using these commands is not suggested based on the fact that the user may be on mobile device, or have JavaScript turned off. Then is it possible to have a simple looking website with all the data displayed if JavaScript is turned off; and if it's not turned off then remove all those elements from the DOM and make a fresh DOM with JavaScript. However the main hindrance to this is converting the data retrieved from database to JSON object so that it can be used by the JavaScript.
I don't think this is possible, but is there some way in which PHP variables can be directly used by JavaScript ?
PHP does never manipulate the DOM, the DOM is purely client side, while php is purely server-side. PHP can generate HTML, which will be sent to the client, and processed to a DOM by the clients browser.
If you want to (nearly) completely split it in two parts, you could split it into an API server (php & database) which will provide a RESTful JSON-API and a content server, which will provide your static HTML, CSS and Javascript files.
The Javascript on the content server will connect to the API server with AJAX get and post requests to retrieve and send data to the database.
Yes, it's entirely possible to do what you're describing. You'd use static HTML files for the basic page setup, the usual CSS and images and such, and your PHP would only be used to generate JSON to return to the client and get used by JavaScript. So for instance:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Example</title>
</head>
<body>
<table id="theTable">
<tbody>
<tr><em>Loading...</em></tr>
</tbody>
</table>
<script src="yourscript.js"></script>
</body>
</html>
yourscript.js:
getDataViaAjax("data.php", function(data) {
var table = document.getElementById("theTable");
// ...fill in the table using the information from `data`...
});
data.php:
<?php
// Get data from somewhere
// ...
// Output it
echo json_encode($theData);
?>
Obviously the table there is just an example. You'd probably have much more static content, and a few places where you wanted to add dynamic content.
This is a perfectly feasible approach, and the separation of concerns helps as the team expands.
However, note that if you do this, any page that has content from the DB will result in two HTTP requests to the server (one to load the HTML, the other — which won't start until after the first one is at least partially finished — to load the data) rather than one. In general, the goal is to minimize HTTP requests. So there are trade-offs.
I don't think this is possible, but is there some way in which PHP variables can be directly used by JavaScript ?
Correct, that's not possible. There are frameworks like Meteor (that one isn't PHP-based) that handle the middle layer for you, though, and make it seem a lot like that's happening.
You can also look at tools like AngularJS and KnockoutJS that can bind your JavaScript data objects to DOM elements, saving you a huge amount of manual update code, or even just things like Handlebars that render templated stuff for you.
I think what you are looking for is a client-side template engine, where the document is built client-side using ajax queries. The ones I have heard good things about are Handlebars and Mustache, though I'm sure there are others to choose from.
But even with such a solution, I imagine that some amount of server-side HTML needs to be output to "prime the pump", in which case, you would want to consider a server-side template engine like Smarty or whatever the latest-and-greatest equivalent is. With a server-side template engine, you would write the templates as standalone files (like .tpl for Smarty) and PHP would consume the template as an object and then pass in any unique variables for the template via the template-engine's methods and then you would call the display method for the template.
In either scenario (or a combination of both) you are separating your final HTML output from PHP so that PHP is interacting with the templates rather than doing plain echo "<div>This looks so Web 1.0</div>"; which I think is what you are trying to avoid.
Currently I am creating a website which is completely JS driven. I don't use any HTML pages at all (except index page). Every query returns JSON and then I generate HTML inside JavaScript and insert into the DOM. Are there any disadvantages of doing this instead of creating HTML file with layout structure, then loading this file into the DOM and changing elements with new data from JSON?
EDIT:
All of my pages are loaded with AJAX calls. But I have a structure like this:
<nav></nav>
<div id="content"></div>
<footer></footer>
Basically, I never change nav or footer elements, they are only loaded once, when loading index.html file. Then on every page click I send an AJAX call to the server, it returns data in JSON and I generate HTML code with jQuery and insert like this $('#content').html(content);
Creating separate HTML files, and then for example using $('#someID').html(newContent) to change every element with JSON data, will use even more code and I will need 1 more request to server to load this file, so I thought I could just generate it in browser.
EDIT2:
SEO is not very important, because my website requires logging in so I will create all meta tags in index.html file.
In general, it's a nice way of doing things. I assume that you're updating the page with AJAX each time (although you didn't say that).
There are some things to look out for. If you always have the same URL, then your users can't come back to the same page. And they can't send links to their friends. To deal with this, you can use history.pushState() to update the URL without reloading the page.
Also, if you're sending more than one request per page and you don't have an HTML structure waiting for them, you may get them back in a different order each time. It's not a problem, just something to be aware of.
Returning HTML from the AJAX is a bad idea. It means that when you want to change the layout of the page, you need to edit all of your files. If you're returning JSON, it's much easier to make changes in one place.
One thing that definitly matters :
How long will it take you to develop a new system that will send data as JSON + code the JS required to inject it as HTML into the page ?
How long will it take to just return HTML ? And how long if you can re-use some of your already existing server-side code ?
and check how much is the server side interrection of your pages...
also some advantages of creating pure HTML :
1) It's simple markup, and often just as compact or actually more compact than JSON.
2) It's less error prone cause all you're getting is markup, and no code.
3) It will be faster to program in most cases cause you won't have to write code separately for the client end.
4) The HTML is the content, the JavaScript is the behavior. You're mixing both for absolutely no compelling reason.
in javascript or nay other scripting language .. if you encountered a problem in between the rest of the code will not work
and also it is easier to debug in pure html pages
my opinion ... use scriptiong code wherever necessary .. rest of the code you can do in html ...
it will save the triptime of going to server then fetch the data and then displaying it again.
Keep point No. 4 in your mind while coding.
I think that you can consider 3 methods:
Sending only JSON to the client and rendering according to a template (i.e.
handlerbar.js)
Creating the pages from the server-side, usually faster rendering also you can cache the page.
Or a mixture of this would be to generate partial views from the server and sending them to the client, for example it's like having a handlebar template on the client and applying the data from the JSON, but only having the same template on the server-side and rendering it on the server and sending it to the client in the final format, on the client you can just replace the partial views.
Also some things to think about determined by the use case of the applicaton, is that if you are targeting SEO you should consider ColBeseder advice, of if you are targeting mobile users, probably you would better go with the JSON only response, as this is a more lightweight response.
EDIT:
According to what you said you are creating a single page application, if this is correct, then probably you can go with either the JSON or a partial views like AngularJS has. But if your server-side logic is written to handle only JSON response, then probably you could better use a template engine on the client like handlerbar.js, underscore, or jquery templates, and you can define reusable portions of your HTML and apply to it the data from the JSON.
If you cared about SEO you'd want the HTML there at page load, which is closer to your second strategy than your first.
Update May 2014: Google claims to be getting better at executing Javascript: http://googlewebmastercentral.blogspot.com/2014/05/understanding-web-pages-better.html Still unclear what works and what does not.
Further updates probably belong here: Do Google or other search engines execute JavaScript?
On a website that I manage, we have JSON files which contain page data. We then create the page using this JSON.
The data looks roughly like this (except a lot more complex).
[
{"title": "Hello world", "content": "World, hello to you!"},
{"title": "Hello world Part II", "content": "The sequel to hello world."},
...
]
This data is then parsed into HTML. Now, here lies the issue: we need two versions of the HTML.
One needs to be static, outputted in the format of file-0.html which would be formatted with a title of Hello World and content of World, hello to you! and file-1.html (title=Hello World Part II, content=The sequel to hello world).
The second needs to be just a plain page file-all.html which includes a JavaScript that pulls the JSON via AJAX when its needed and creates a container for each page which includes subpages that have the content/titles for everything in the JSON.
Right now, we use Python to generate the HTML for the file-0.html static pages, and then JavaScript for the AJAX pages. While this works, it means there is a lot of code duplication for a pretty small project—every time we want to change the class of the <h1> title is wrapped in, we have to change two places with slightly different syntax.
Is there any good way of fixing this issue, so that all the code for generating page (or as much as possible) is in one language? (This would probably have to be JavaScript, since bandwidth is an issue—we'd like to avoid transferring HTML via AJAX if possible.)
You have two good options:
Write the page generation logic in a template language like Mustache (http://mustache.github.com/). Then you can compile those templates down to Python (for the server side) and Javascript (for the client). The data consumed by both versions is the same and you only have to maintain one template definition.
Write everything in Javascript and execute that JS on the server. There are at least two good server-side JS engines: V8 and Apache Rhino.
You can use the server to render the page and grab that with an AJAX response. While this avoids code duplication, it might be less efficient since you have to query the server to render each page, rather than making the client do it themselves (this might not be too much of an issue, though). It shouldn't take up too much bandwidth, since it's just HTML (unless you're throwing in templates from all sorts of places). This approach, of course, only works if you're using a dynamic web site.
Alternatively, you can implement all the rendering logic in JavaScript and use something like PyV8 to run it from within Python. I question the efficiency (and sanity) of this, though.