Which is better practice? Getting HTML from Jquery Response - php

This is just a question as to find out what and how people do this, but
Say a user adds something to a list, when it's done, it runs the ajax below and updates the .user-stream-list
$.ajax({
url: "user-stream-list.php",
success: function(data){
$(".user-stream-list").html(data);
}
});
but the user-stream-list.phpresponse for example is
<li class='feed'><a href='http://www.theverge.com/rss/index.xml' data-fid='13' data-uid='15'><img class='favicon' src='https://www.google.com/s2/favicons?domain=www.theverge.com'><span class='title'>The Verge - All Posts</span><span class='options'><span class='addcat' data-fid='13'>+</span><span class='delete'>×</span></span></a></li>
Would this be acceptable in web development? Or should I really be passing it through as json and sort it into html afterwards?

Do what works for your particular problem. Good design finds compromise between the trade-offs. If you are on a tight deadline and you need something that works and it is easier to return HTML from PHP do it.
That said, you are generating the HTML programmatically on the server. You have same job if you pass JSON, the difference being the client generates the HTML. That is far more flexible for you, as you can generate different HTML in different contexts. Or not even HTML at all.
Designing to return a flexible data structure loosely couples your application components by affording reuse: the data structure remains agnostic to the caller's environment and the target presentation. This flexibility will serve your application well as it grows, and - in my opinion - the effort to design such an API early on is worth it.

I agree with bishop's answer, i think it depends on the architectural design of your system. If for example you want to use a js templating system, create a mobile device system, serve your data to other systems or something else that communicate with your back end then it is best to serve json from your server.
However even if you choose to prepare HTML server side using php, which is very common and acceptable as others noted in this thread, it is best to separate the entities creating the data and the ones creating the html code/template in order to be flexible and have the best of both worlds in the future.

If I understand you right you are worried if you should pass complete HTML code from the server or simple just the data. Well both approaches are good. It all depends on your needs and implementation.
For example you may want to add some inline styles to certain items in your list. You can generate that on the server side which would be much easier and send the whole HTML code. You may also want to add some microdata. Passing each of this parts separate as JSON would be unnecessary.
On the other hand you may already have premade HTML code and you only want to insert data into it. In this case passing the whole tag would be a waste of bandwidth.
There are also other factors you need to consider like: would it be faster to compile the data on server side or on the client side, do I need to save bandwidth or can I allow myself to send as long messages as I want?
In general try avoiding 2 things: sending large chunks of data and doing the same job twice.

Answers to this question could be broad, and are very opinion based, however I'll give my 2 cents.
Since you tagged the question as PHP, I assume your application is primarily PHP based for the server side code. Since all of your views will be generated by PHP, I'd keep all templating on PHP's side. Why? Maintainability and clarity. Having to chase down different sources of view generation is time consuming and misleading. IMHO it's better to keep all of the logic in on one side/language, and something like client-side JavaScript should be used for things a server side language cannot do (AJAX, transitions etc.).
This approach will allow for a smarter (IMO) view generating, its also very clear and makes it easy to alter your templates/views (remember, you should be writing code with other people in mind).

Related

Reuse a backbone application on the server side to render a view on the server side

I am working onr a backbone.js app, where one of my views is a complex feed with different types of subviews.
I will have to generate a static version of that view to be usd for email purposes. I am looking for the most practical solution that will allow me to reuse as much as I can from the existing code without duplication
I came up with two options:
Generate the view statically using php. This will men that I will have to duplicate a lot of the logic because of the different languages.
Set up a simple nodejs http server which will reuse most of the app logic to create a view on the server side. This sounds nice, but I am still unaware how practical such a solution will be in the long run. For ecample, I am completely unaware whether I would be able to use Jquery on the server side to create the layout from an existing html file.
Which one of he two options should I go for and why? Or perhaps there is a third one?
I debated a long time about this exact issue when I started working on my first backbone.js app, because like you I thought it would be a waste to duplicate so much view code. I'm working in rails, and my goal was to use the same format (haml) for partials on the server (haml/ruby) and templates on the client (haml/coffeescript), but that proved to be impossible and anyway not very advisable.
Anyway though, after having worked on the app for several months, I've come to the conclusion that the duplication is not a major issue. It certainly is not worth it trying to avoid duplication if the end result is only a couple of pages. Also, in my case at least, the static page I'm sending from the server did not end up having exactly the same structure as the templates that backbone.js renders, so it's not 100% duplication anyway.
Not sure if that helps, but in any case I'd suggest first duplicating the page and see how much extra work is actually involved. More complex solutions like #2 with the nodejs server strike me as overkill unless you'll really be serving a lot of pages this way.
For what it's worth, here are a few discussions of the topic on SO:
Rails Client side / Server side rendering using single template (handlebars or Mustache) with Sammy.js
Template language that works on both server and client

Pros and Cons: Writing HTML in PHP

(I'm using google translate)
I separate my HTML and PHP, just for good programming practices in MVC.
However a lot of the time I come across someone on staff writing HTML directly in a PHP file.
And during the discussion of 'don't do that, it's bad, it's not a good practice', I haven't got any technical arguments, apart from 'it's not good practice'.
And they always say, 'I am not bound to get stuck on details."
Technically, because it isn't recommended?
It is not recommended because the past has shown that the longer a routine or script grows, the harder it is to manage. If you need to deal with HTML and PHP in one file, you need to write more than if you would have separated the code into two. Which brings me to the point that you write more in one file with HTML and PHP which results in more complex code.
This is only general. There are programmers out there who don't have a problem with larger code-chunks and who don't have a problem with mixing languages in the same files.
At first sight it might even look easier. However, as software tends to become more complex as it grows, after some time of growth it's worth to think about how to modularize the code, e.g. to separate the view from request processing.
One common line that is drawn between components is then between the output (display) and the processing. The processing will interface with the output layer then instead of having both jobs in one script/routine (processing and display of output). Actually the output is factually abstracted / normalized / reduced to make the output code work on it on it's own. E.g. instead of outputting HTML to the browser, the processing will pass objects to the output layer and the output layer will convert it into HTML then (the meaning of object is broad here, can be a variable, an array or an OOP object).
If you are developing together with someone else, you should decide together where to draw these lines so you can actually work together. You're both doing something wrong because like you write in your question it's not clear how you can work together. Working together is more crucial than favouring one design over the other. If you think your colleague is wrong, you both need to discuss the issue.
In my opinion you can think about it like this.
If the PHP-code is related to how the information is being displayed to the user, then it is OK to have it in the view (if you are using an MVC approach) or mixed in with the HTML. Sometimes you need small pieces of code to display the information as you want, "if this date is passed then show it like this, otherwise show it like that".
In any other case, you should avoid mixing your PHP with your HTML, for the purpose of structure, ease of maintenance, DRY and so on.

Outputting data with JQuery & PHP

I have a general question regarding quality of writing code ...
I'm working on website, that outputs data from MySQL with PHP and it is being called with $.get() / $.ajax() with jQuery....
Now my question is .. the data I´m exporting for example: an array of comments (from class Comments) for a specific post, and this array is being returned from PHP as a string with its HTML manipulation (return '<div id="this->$data"> this->$data</div>';) and with the JQuery manipulation, I´m adding all the comments as list elements or anything else to a specific html element.
Is it useful to do this? Or it is better to send the array in a variable to jQuery, and then work with its elements and make the dynamic html code directly in JavaScript/jQuery..
If that was confusing, is it better to generate the html code in PHP when returning /echoing, or to generate the html code in jQuery after receiving the core data from the php?
I know there are other methods like XML JSPN, I'm just asking here about the efficient with generating HTML to manipulate core data (example: Array or Core Json data)
Let me elaborate on AlberVo's answer
The PHP file which is generating the data, if it is going to be called from possibly other sources, say from an iPhone app, or a command line application or a desktop application, or even if say 2 months down the line you think your website's front-end is going to be say Flash based, then its better to keep your PHP code front-end agnostic and just return xml/json/yaml.
If you know its going to remain a HTML/Javascript based front-end and front-end load speed is an issue, then you can do all the hard work of converting your data into HTML in the PHP file.
In the end personally, I'd say stick to just generating front-end agnostic xml/json/yaml. You never know what direction of the code the future may bring. And architecting your design this way keeps you flexible a.k.a your front-end and middle-tier are loosely coupled.
A few more advantages to such an approach (which really just arise from the loose coupling)
Work organization. If in the future someone else is also working on this project one of you can work on the middle-ware and the other on the front-end as long as you respect the json/xml/yaml in between. Your work is not going to affect the other's.
Testing. Using a xml/json/yaml also allows you to unit tests your PHP code and front-end easier. Your test data is just xml/json/yaml.
The way I decide on this is if I foresee using the data for things other than that specific use, then it is better to return the raw data such as json or xml.
You will want to consider which part of your application should control your page structure and layout. Do you want your page structure to be defined by the PHP script that just returns data? Or do you want to define the page structure in the page itself, and let the PHP script just return the data as needed.
This is an issue addressed by the MVC (Model-View-Controller) pattern. If you follow the MVC pattern, you will separate logic from presentation, rather than mixing the two. This allows your application to remain as flexible as possible, and also promotes code reuse.

PHP MVC with pure Javascript View : good practice?

My question might not be understandable enough, so let me explain the situation :
I'm working on a big ajax webApp built, server side, with PHP using CodeIgniter. This framework saperates clearly models, controllers and views. The view files are rendered in HTML and then sent to the client that does some js treatments on it (like attaching events).
This way of working seems strange to me, as it separates the view between the server side and the client side.
I was thinking about moving all the View treatments to the client part that will build dynamically its html in js. The server side will then send only raw data.
I worked this way on smaller projects, and I was really happy with the result (easily understandable, portable and reusable).
Is it a right way to implement an MVC app ? Any advices around that reflexion ?
I've done pretty much what you are describing on a fairly large data services app as an internal application. In my case I was using ExtJS for the client-side rendering/views, and was communicating to a C# WCF endpoint exposed on the web server. Essentially requests were made/submitted and responses were serialized to/from JSON. It ran very smooth, once some kinks were worked out. The original author had written a custom serializer to do direct results from their data layer directly... this leads to a lot of extra data going down the pipe. As long as you are judicious with your payload data it can be very effective.
Some caveats though...
You should probably avoid this if you expect users without javascript enabled to be able to access the site (anything involving money transactions from external users).
You will want to document your methodology as clearly as possible.
Finding developers for maintenance tasks after you have implemented your application will be very difficult. (many server-side devs are shy of, scared of, or just plain inneffective with JS skills.
For the most part it's a toss up, I find that most people at least have JS enabled, but may have other things blocked off. AJAX/XmlHttpRequest supports is nearly universal at this point.
As to templating for client-side display, there are a few options there (but that's a separate discussion).
Building JavaScript views works fine within the MVC pattern, since your view is not mixed in with your business logic or model.
However, there are a couple drawbacks to using full javascript views. Mainly it eliminates the ability for graceful degradation if the client has javascript turned off. Also, some browsers (IE) don't have a very fast javascript engine, which will make your page load more slowly. It is true that some of the view is separated between the client and the server, but it kind of makes sense when you think about it.
In most cases the HTML that you send to clients is the same for everyone (unless you are doing browser detection on the server side). However the JavaScript routines are different. If you are using a library like JQuery, this will be hidden from you, but the code that is running on each client may differ greatly. One example of this would be the XMLHttpRequest that is used by firefox/webkit etc browser and the active x control that is used by IE. Since the html portion of the content is the same for everyone it makes sense to build on the server, and since the JavaScript portion of the view may differ, it make sense that it is built on the client side.
HTH
I started using the same approach: JavaScript for the user interface layer and PHP for the database access layer. I'm using AJAX to pass all the data back and forth between the 2 layers. So far, AJAX has occasionally frozen on me, but it has been speedy enough most of the time. So I guess it'll work well enough.
(The result is that my code has gone from 90% PHP with 10% JavaScript...to 65% JavaScript with 35% PHP.)
I've also separated the code for my page views from the code for my triggered event action functions. So I like to think that I have an MVC arrangement now (even though I'm not using an off-the-shelf MVC framework like Backbone.js).
I'm not using HTML templates, though. I don't think it feels natural to have 100% separation between HTML and programming. I think simple programming loops, conditional statements, and JavaScript triggers all go nicely with HTML.
If you will think it in the way that there is the main view that creates the html/js engine and couple of ajax views with the data streams - it will be quite OK in MVC terms imo.
Is there anything more dynamic going on on the site itself? Does it do more AJAXy things, dynamically refresh parts of the site etc.? If so, it may be reasonable to have a Javascript-only site.
Since this is not how the web traditionally works though, sending HTML from the server is still the baseline. If your pages are basically static, if you want to serve older clients, an audience that may have disabled Javascript, an audience that may have accessibility problems with Javascript-only pages, alternative clients that cannot understand Javascript or search engines, you should serve HTML pages from the server. There's nothing wrong with it, it's straight forward, simple and foolproof. There are many things to consider when reinventing the wheel in Javascript on the client side. Unless you have a good use for the potential this offers (see for example the highly dynamic Facebook or Twitter pages), it may be more trouble than it's worth to your users.
It sounds like you are one step away from going from the MVC pattern to the MVVM pattern.
MVVM is ideal for complex user interfaces (which is exactly what you would be creating with all the AJAX and JavaScript and whatnot) because in this case your HTML view will be able to act as the controller via JavaScript. There is a library (warning: I've never used it but it looks promising) for this called Knockout JS.

Should PHP frameworks generate JavaScript?

I've noticed that a PHP frameworks; Zend, Cake, and Symfony; seem to either generate JavaScript or allow it to be embedded as a string into the PHP itself. Is this a good idea? From people who've used these frameworks/libraries, what has been your experience working with the Ajax and JavaScript helpers? Has it been easy to maintain? Does it cut down on development time?
No it is a bad idea,
Generated javascript usually means that the site won't even function without it (like many asp.net sites). If you want to do more complex things or want to enhance accesibility there is no other way around than clearly seperating HTML from CSS and Javascript.
Seperating Javascript also makes your code more maintainable as you do not need to have your client side frontend developers mess with your PHP code and the other way around.
The best way to use Javascript is to first let php generate your html, then at the bottom of that page include your javascript files and use functionality like onDomReady. This also doesn't force you to use a particular library just because your framework is using that as base for its generated Javascript.
This is quite a subjective question, but personally, I wouldn't want a back-end framework to do this for me. It's better to keep a clean seperation between business logic, presentation, and client-side UI behaviours for a number of reasons:
More maintainable applications.
Easier to test individual components.
Easier collaboration. Different skill-sets can work on different areas.
Should help ensure your application does not rely on JavaScript in the end users environment.
Personally, I like to write my Javascript by hand, unobtrusively so that i just have to add an extra event to document.domReady with for example the correct parameters. That little trigger function then gets the ball rolling.
Best practice of the day:
Keep frontend-code and backend code
untangled as much as you can
I would say it depends, like anything. There is certainly some value in having "smart" server side widgets. For example, a widget that "knows" how to update itself through AJAX, or a form which can handle client side, and server side validation. The latter is an example of which it would be costly and time consuming and error prone to rewrite boring validation code in the client. It doesn't require rocket-science javascript, so as long as your framework can handle it unobtrusively, I would actually advise this route.
Additionally, framework code that will handle GUI stuff also (a la ext or something similar), is also not a bad a idea.
However, anything more complicated than that, please use Javascript itself.
I personally love writing my own Javascript so I don't really want it written for me, but I don't see it as being particularly 'dangerous' or 'harmful' to have frameworks that do it for you, as long as it is properly done. My biggest problem with them is that most of them will work as long as you want the standard behavior of a feature, but as soon as you want something a little different to meet your project's needs better it takes so much work to customize it you would have been better served to do it yourself. At least that was my experience with CakePHP's javascript automation.
My experience with the Javascript and Ajax helpers in CakePHP has been very positive.
They have allowed server-side developers to prototype and build features that otherwise would require someone with real client-side experience to do, all without having worry about the quality of the javascript code they "write" and leaving the real front-end engineers free to focus on the advanced client-side features.
It's not a good idea for the PHP to generate Javascript. The only javascript I would recommend exporting is simple JSON assignments like the following:
<script type="text/javascript"><!--
var MyNamespace.info = <?php echo json_encode($info_array) ?>
// --></script>
This is the easiest way to sanitize PHP information and let it be accessible to javascript on the client. However, anything else should be written in actual JAVASCRIPT FILES that are referenced with tags at the head of the document. The only other appearance of Javascript from server-side files, that I would say is alright, is stuff placed into "onclick" and other such attributes.
The rationale for this is that the Javascript should be written and maintained by front-end people who know Javascript, and the site should be able to work (at least partially) without javascript. There is no reason to generate spaghetti Javascript inline.
Check out my PHP framework, PHP On Pie (http://phponpie.com) for an example of how to implement this properly. It keeps the JS and PHP separate, except when exporting JSON as shown above. However it also provides conventions for easy interoperation between the client and server via AJAX.
I believe you should keep languages apart. Even though they can complement each other. That way you can pick the implementation of said language and create a mix that fits you perfect.
I think there is definitely a place for generated javascript. (1)
The number one reason for generated javascript is ease of maintenance. Any dependencies are explicitly encoded and configured from the framework (PHP, ruby, scala, python) itself. For instance if you move your assets or change the upload directory, just update the configuration and watch things Just Work.
Need client side input validation to take some load off your server? (2) Let the framework generate correct validation code derived directly from your data model for you. With generated, javascripted population your framework can serve pre-rendered, static HTML forms from the cache. This could be a huge win if your forms contain lots of selects and options.
1) Assuming that the client has decided that it's OK for the site to depend (more or less) on javascript, with all the caveats that entails. Graceful degradation may or may not be possible or desirable.
2) You need server side side validation too, but you knew that, right?

Categories