Please redirect me if a similar question exists.. I haven't been able to find anything, though I'm sure that my problem is fairly common...
I have a page that has 5-6 divs that can be individually loaded through Ajax requests. Through a prototype ajax.request(), the server (php) echoes back the HTML code for the division before the client refreshes the divs's innerHTMLs.
Here's my question : What's the best practice for preserving the MVC pattern on the server side concerning the HTML code it throws out?
For now, my models return database data to the controller, enabling it to initiate a really long var containing the HTML code that it then echoes. My problem is that I end up with a lot of HTML code in my controller classes...
You could use JSON for transporting data to the client-side and constructing it there.
That way you'll have an abstracted data source not bound by your markup. JSON can be directly evaluated into a javascript object.
Do you really like to use MVC? The C can mostly be removed by Conventions / RESTful URLs.
Like Andy said, you should use JSON to transfer the data to the client side. XML is also a wide used alternative (because it acts much better if other apps have to use your services). XML can be tranformed easily to JSON! And JSON code is valid JavaScript Object code. So you can use it to stich client side templates together with it.
You should try EJS for browser/client side templating! If you do so, you have no HTML boilerplate in your controllers! Just business logic. That follows a lot of SOA best practices. The architecture pattern is called SOFEA or SOUI (which is the same).
I've written my homepage with it. The evaluation of a lot template engines has clerified that EJS is the best candidate.
Because:
1. It's fast!
2. It's free (MIT License)!
3. It works well with JQuery
4. It does realy modify the DOM, so other methods can access the used templates (JS Repeater doesn't).
Other frameworks:
JSmarty: Not such as easy to use but it can use Smarty templates. It isn't enteprise prooven and still under heavy development.
Trimpath Javascript Templates: Doesn't work well with JQuery/Prototype... Also still under development.
jQSmarty: Nice, but it seems that the development has stopped. The last change was in 2008.
seethrough_js: Invasive template layouting. Nice for Erlang people.
JsonML: Also an invasive template format which is based on JSON. What do you think about it? I think designers should stay at their HTML/CSS elements, so no knowledge is wasted.
JS Repeater: Reminds me at my own bad tries. I've checked it out and used it.. but it doesn't handle a lot of things very well. (Such es empty fields etc.)
Pure: Time to start a relegios war on how to develop pages? I think that Pure isn't the answer. It's bloating if you define what's really to do and it fails to scale like JSF. It has no invasive syntax, thats very good. But the price of the hard to use rules for rendering issues are a no go for me. It just feels don't right. I've met other people which think completly different! Test it out and let me know what you think.
This is what I do for MVC + AJAX...
Really simple implementation, if you were to ask me.
http://jarrettatwork.blogspot.com/2009/02/aspnet-mvc-ajax-brief-introduction.html
If think that the most important letter in MVC is V for working with AJAX. AJAX with HTML, and JS is part of presentation layer so by theory it is place for View - part.
View is responsible for what you send to end user, and MVC patter is there not only to separate Model, View and Controller but to enable us multiple views for the same data model provided.
So it is best to encapsulate code in a class and use that same controller code to render different views. In first case that could be drawing of a static page, but in other scenario it is view specially designed for AJAX calls and data may be in JSON or other standard format it doesn't matter, as long as you respect responsibilities that every layer has.
If the HTML is mostly in string literals, as I understand it is, you probably should move the HTML outside the <? ?> tags altogether and insert the dynamic contents from the database with small inline PHP snippets that reference variables set by the controller.
This is effectively a template mechanism. Remember, PHP is at its heart a template engine.
Example:
<?php
include 'controller.php'; // set variables used below
?>
<div>
<h1>Hi there, <?=$UserName?></h1>
<p>Since you've been here, <?=$numberOfDays?> days have gone by</p>
</div>
etc. This also gives you back the syntax highlighting in your HTML and gets you rid of having to concat all the long string literals inside your PHP code which often messes up the readability of the code.
Related
I've found a framework that handles the views in a different way than just plain html. To be honest, I've no idea how are the big frameworks handling this issue because I've mostly worked with some tiny frameworks, so that's why it was an interesting thing for me. A quick example:
Instead of writing
<h2>Click on this example</h2>
You'd have to type
echo $html->h2('Click on this' . $html->link('www.example.com', 'example'));
So, my question is which one is better? Isn't plain html going to be faster? And let's say more understandable for others? Or let's leave the understandable part away, I want to know more about the performance and maybe other stuff that people know and can be mentioned on this issue.
As everything in the programming world, it's a matter of taste.
Though, I'm strongly against it, for a few reasons:
It makes writing your views harder for non-PHP-programmers.
Annoying to debug later on
I like to see my views the same way as the browser will.
Adds a lot of overhead to pretty simple stuff
Looses the pretty (and logical) HTML indentation
UGLY!
HTML issues are easy to spot anyways, if you are indenting your HTML markup correctly.
So for me - plain HTML all the way.
Though, some view helpers are great - creating links, handling element classes, validation, etc.
In my opinion, try to find the sweet spot - don't clutter your view with too much PHP, but don't give up on making sure your code is as dynamic as it could be.
You just cant say so... Usually, MVC framework divides codes into modules which makes the site clean by separating database actions, logical actions and views. There are also other cases like sending mails, paginations, image processing and manipulations etc which are complex tasks in plain programming and can be done in few lines in MVC because every thing is predefined. The example you defined above is only to follow the pattern but you can use it other way too.. So, it an alternate. You can use it either way. so, whenever you find that in certain cases the MVC could be complex, you can do that in your own way. So, I guess its more flexible by giving us the option of both ways.
Hope that answers your question.
I have personally worked with the Yii PHP Framework, and even that has its way of handling HTML views(CHtml), though it was my choice to use either. The interpretation that rendering plain HTML is faster than writing it in some code which is interpreted by the framework and then generated as HTML make sense, and as a matter of fact, I do think plain HTML is faster.
However this allows better flexibility in creation of dynamic HTML content, like form support methods (validation, etc..), and other helper methods. Also I think this has evolved more from the Object Oriented Programming obsession.
But it'll only be a matter of time before you get used to it. And if you think about performance, think that it isn't really going to make a difference.
CodeIgniter is one of the frameworks that provides an HTML helper to allow you to generate HTML through PHP code (like the latter case in your question).
While this will be marginally slower, the advantage is it ensures valid HTML is output. Take this example:
<h2>This is a header without a closing tag
The above is a common mistake which will fail silently. However, you cannot make the same mistake if you use the HTML helper function
echo heading('This is a header',2);
As for readability, anyone familiar with PHP should be able to understand either code fragment with little to no difficulty.
My problem is actually not the ajax loading itself, more the capability to load it without javascript. I mean, I cope easily when I code my whole project just based on ajax-availability OR just without the use of ajax.
//EDIT: Although Arend already had a more or less valid answer, at the same time 'there is no direct answer to this question'. However, I'd like to see some other approaches of developers for scenarios like mine though! Even just a few links can help!
Basically I just get frustrated, coding everything twice on the same page to make sure that both users without and with Javascript enabled have the same experience. It's annoying and I was always wondering how others solve this problem.
When I update for example two divs with dependency on the same variables, it gets messy. Here's an example:
non-js-version
require 'classobject.class.php';
$another_var = 'something';
$class = new classobject($_POST['variable']); // just an example to show that this is dynamic - I'm aware of injection!
$function = $class->returnsth(); // returns 1
if(isset($_POST)) {
echo '<div id="one">Module 1 says:'; $require 'module_one.php'; echo '</div>';
echo '<br /><br />';
echo '<div id="two">Module 2 says:'; $require 'module_two.php'; echo '</div>';
}
Now in module_two.php and module_two.php I have code that executes differently depending on the return variable of $function.
Like:
if($function >= 1 && another_var != 'something') {
// do stuff
}
else {
// do other stuff
}
Now as this works easily with a reload, when I want to load the two modules on keyUp/enter/submit or whatever, I have basically a few problems:
I have to send the $_POST variables manually to the modules to use them
I have to re-execute the class & it's methods and make a link (require_once) to them in each of the module-files.
As $another_var is not existent in the modules, I'd have to send this variable to each modules, too (with post for example) and then before it can be used, I'd have to 'change' it like $another_var = $_POST['another_var'];
I find this mildly annoying and I wonder how you guys do that. I hope my way of coding is not too silly, but I can't think of another way. It's probably hard to relate to my very basic example, but to bring a whole project with the code would be too much. To sum it up, I'm looking for a better way to code and clean this mess up - there must be a way! I thought about sessions, but for compatability I don't want to rely on them either (if someone doesn't allow cookies).
In case you can't relate to what I'm trying to accomplish with that way of having my code assembled, I'll explain a scenario I'm facing quite a lot (not important if you already understand my misery):
Basically I have my index.php page where everything gets executed, with the html body and css styling and so on. This page expects some variables, that get set from the page that requires the index (like $another_var in my example).
Now other variables can get set too (from a form for example). Depending on that different classes and methods load new variables (arrays) that get used in while-loops in my modules to echo everything out.
Hope that's not too abstract. Think of a booking system where some variables are set from the page you are coming from (the event you want to book) and then a few more things get set by the user (a timespan, some preferences,...). In the end it's supposed to show results from the database all the way to the end-result - you can say the user narrows the results from step to step.
There is no direct answer to your question, but there is some food for thought.
Seperation of concerns
You can think about if you can perhaps seperate your buisness logic and layout logic. Often the use of a template engine can help greatly with that. I've had positive experiences with for example Twig or Smarty (was some time ago, not sure how they measure up right now). It requires you to write your code in a (less linear) way, but more logical.
A typical example of an OOP like seperation of concerns might be something like this:
$this->setParam('Myparam','myvalue');
if ($this->isAjax())
{
$this->setTemplate('ajax.php');
$this->setLayout(false);
} else {
$this->setTemplate('normal.php');
$this->setLayout('Mylayout');
}
return $this->render();
It is an imaginative situation, which can be found in many MVC like applications and frameworks. The main idea is that you should have the possibility to seperate your layout from your data. I would suggest looking at some of the modern frameworks for inspiration (like symfony, codeigniter, zend framework).
Glossary / Often applied concepts in a decoupled PHP application
Here is a quick list of concepts that can be used.
Example mvc in php: http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
Note: I don't really like the implementation. I much more prefer the existing frameworks. I do like the explanation in total of this tutorial. E.g. for me this link is for learning, not for implementing.
Silex
For a simple decoupled php micro-framework I would really recommend silex, by the makes of symfony2. It's easy to implement, and to learn, but contains mainy of the concepts described here; and uses all the php 5.3+ goodies such as namespacing and closures.
see: http://silex.sensiolabs.org/
Frontcontroller Pattern
Only have one, and one only point of entry for your code. I usually only have one, and one only point in your application. Usually a frontcontroller 'dispatches' the request to the rest of the application
http://en.wikipedia.org/wiki/Front_Controller_pattern
Routing
A routing system is often used in combination with the frontcontroller pattern. It basically describes which URL is connected to which module / controller. This allows you to change the way people access your app without changing the urls.
See: https://stackoverflow.com/questions/115629/simplest-php-routing-framework
Controller
A controller is the place where buisness logic is applied. Getting the data from the database, checking privileges, setting the template, setting the layout, etc. (although this is also moved outside the controller if it becomes too big of a seperate concern).
Model
The model basically is the layer in which use manage your database. This can be a simple class where you move all your mysql_* functions, or it can be a full-featured ORM. The main philosphy is that all the logic related to fetching and placing information in the database is seperated.
One step up: ORM
An often used method in applications are Object Relational Models, these 'map' SQL records to PHP objects. Doctrine and Propel are two of these well worked out libraries. I heavily rely on these systems in my development. In this sense, the doctrine or propel part will represent the model layer.
Doctrine: http://www.doctrine-project.org/
Propel: http://www.propelorm.org/
Other ORMS: Good PHP ORM Library?
PHP ORMs: Doctrine vs. Propel
View:
The view usually consists of a templating engine. Some use plain PHP as a template, others, such as symfony create a seperate scope in which variables are placed. There are many discussions and opinions about what is best, one is right here on stackoverflow:
Why should I use templating system in PHP?
PHP vs template engine
Ones I like:
- Twig: http://twig.sensiolabs.org/
- sfTemplate: http://components.symfony-project.org/templating/
- Smarty: http://components.symfony-project.org/templating/
Decoupling mechanisms:
Event based systems
Using events in your can help to seperate the code. For example if you want to send an email after a record has been saved, events are a good solution to do that; in general the model should not have to know about email. Thus events are a way to connect them: you can let your -email-send-class listen to certain records in order for them to send the right email. (Perhaps you'd rather want your e-mails send from your controller, this is probably a matter of taste).
Dependency injection
When using OOP code in PHP many relied on having singleton classes running around (configuration, etc). From an OOP point of view, this can be considered bad, because it's hard to test it, and it's not considered very elegant to have dependencies running around like that. Dependency Injection is a pattern that came form Java and is now used in the newer frameworks to get around this. It might be a bit difficult to wrap your head around, but you will see it coming back in several new frameworks.
Dependency injection in php: Dependency Injection in PHP 5.3
Frameworks:
A lot of these methods are difficult, or a lot of work to implement yourself. Many will reside to a framework for this. You may or may not need a framework. You may, or may not want to you a framework, it's your choice. But it's still useful to learn how the frameworks do it, and not try to reinvent the wheel yourself.
The no-framework php frameworks: https://stackoverflow.com/questions/694929/whats-your-no-framework-php-framework
Good habits: https://stackoverflow.com/questions/694246/how-is-php-done-the-right-way
Frameworks worth looking at (imho): CodeIgniter, Kahona, CakePHP, Symfony (1.4/2.0), Silex, Zend Franework, Yii. There are many many more, each with their dedicated fans and haters.
I wrote something like this with PHP. I already had abstracted the rendering of every page such that I define a $content variable and then require('layout.php'). The $content variable is just a big HTML string.
I wrote a PHP function to determine if request was AJAX or not.
The non-AJAX responses render the layout with $content in the middle, b/t header and footer layout content.
AJAX requests basically get this: json_encode(Array("content"=>$content)). And I use jQuery to get the HTML out of the JSON response and modify the DOM. Using json_encode() will handle escaping the string for javascript.
In the end, I effectively have AJAXified every page w/o over-engineering a complex solution.
Any browser that supports AJAX can also open a link in a new tab/window to simulate the non-AJAX request. (Or bookmark/share a link, too.)
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.
I'm going to write a CMS, but right now I'm writing down all my ideas and trying to get all of my concepts straight before I start. One of the things I'm torn on is whether to use a template language and parse the pages of the website, and replace template tags with content items, or just develop the site with straight PHP and have the CMS generate data structures which help. For example:
{navigation: products}
vs.
foreach($cms_label['products'] as $product) {
echo '<li class="product_nav">'.
'{$product.name}'.
"</li>\n";
}
The former is cleaner but it would involve inventing a language, plus parsing every page before display. The latter is less clean but I think it could work really great if the CMS just provided data for all the code. But, would this be considered mixing logic with presentation? Another alternative I've considered is using PHP functions that are similar to the template tags:
<?php navigation('products'); ?>
What are your thoughts?
Keep in mind I don't have to do anything more complicated than including a page at a certain place, or writing out an unordered list; the rest shall be handled by CSS.
Template languages for PHP are an example of an anti-pattern called "Inner-Platform Effect." Smarty is an example of a template framework for PHP, but even Hasin Hayder, author of a book on Smarty says that Smarty is dead and there's no need to use it anymore.
There can be good reasons to develop a template language, for example if you are having non-coder designers or content editors using your CMS and you don't want to overwhelm them with the complexity of PHP (or allow them to write code that could break your website).
But you haven't described that as a goal, so I'd assume using PHP as your page template language is best in this case. It'll be less work because you don't have to develop your own new language, and it'll provide greater flexibility for uncommon cases where you need a specific kind of dynamic content.
Don't write PHP functions to encapsulate blocks of HTML output. Instead, use include() to pull in fragments of HTML. This technique is sometimes called "partials."
You can also use an MVC framework such as Symfony, Kohana, Solar, CodeIgniter, or Zend Framework to help you keep discipline about separating your PHP template code from the rest of your application code.
I was a very happy Smarty user for a long time, I don't believe in specialized template languages any more.
A template language won't prevent you from putting inappropriate logic in your presentation code, it'll just force you to write bad code in the template language.
It's fairly trivial to roll your own little template system that uses php in the templates. Then create various helpers to keep your template code clean (like your "navigation()" function).
I think the approach taken by Zend_View is pretty good. Symfony's view-layer stuff is fairly neat too, but might be a little intimidating. You don't have to use a framework to get something from it. Just look at some of the template code in the examples, and see what inspires you.
Bottom line: forget about a special language for templates -- just apply good design sense to your view code, factoring complexity out of the view scripts and into reusable helpers.
Reinventing the wheel is most of the time a bad idea.
PHP is already a templating language. You don't need to implement your own.
As for Smarty it is the most complete templating system for php and it is still a bad idea.
A couple of articles on the subject:
Once upon a time there was Smarty! by Hasin Hayder. He actually wrote a book on smarty and he doesn't recommend it.
Php and Templates by Harry Fuecks (Author of the 1st edition of the php Anthology)
If you want to look at templates done better look at:
phpSavant it uses php code and still promotes separation of concerns.
The final objective is of course to have easier code to maintain by promoting separation of Business Logic and Presentation
You might want to look into Smarty- http://smarty.php.net Smarty is a very powerful template engine that gives you the best of both worlds. It has extensive support for custom modules and plugins.
I built a custom CMS with Smarty and PHP and have nothing but good things to say about it.
The php code to use Smarty looks like this
<?php
// my cms
$smarty = new Smarty();
.
.
$smarty->display('home.tpl');
?>
The template code is something like this
<h1>{$pagetitle}</h1>
{insert tag="navigation"}
I wonder why noone mentioned what is one of the most important uses of a template language: automatic output escaping.
It's easy to forget a htmlspecialchars() here or there, so a template language that provides directives like {$name} has to make sure $name is automatically passed through htmlspecialchars, with the appropriate charset and everything.
Of course, that also implies that you can specify a different "context" for variable output, such as e.g. alert('Hi {$name|context=singlequotes}!'); where the template interpreter would escape $name's content so that it is impossible to break out of the single quotes, instead of XML escaping it (which should be the default).
Such contexts can also include stuff like int (to force a number), and it can also be extended to accept additional parameters to format the output, et etc.
My 2 cents. Not sure if there's an open source solution that allows for this (would be interested to hear about it!), I rolled my own interpreter for this stuff at work. Since the resulting "intermediate code" is pure PHP, it can also very easily be "cached" (like Smarty and other tpl systems do).
I pretty much like Smarty and I also think controllers should be purely written in XML and models in YAML. This is the only way to enforce MVC.
If the question of performance arises only then compilation to php might be considered as a possibility (albeit a remote one) with the sine qua non condition that it's done in an obfuscated fashion, to thwart eager developers from reading it.
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?