How to create dynamic external javascript files? - php

I am thinking about how some online services create dynamic JavaScript files. These files have the .js extension, but their content is not static. I found a sample file here. It seems that this script is generated with a higher level programming language. I think it is done with PHP or something similar, but I am not sure, and I have not found any documentation about this topic.
Is there any well known way to create these kind of dynamic JavaScript files?

Consider carefully whether generating a dynamic JS file is necessary at all. Instead of generating dynamic JS, you can often simply inject static script(s) and use separate JSON to support dynamic configuration into your page.
If you view source on this (or about any) StackOverflow page you'll see that they're using this same pattern: Static external .js files that reference a separate centralized chunk of JSON for configuration. That JSON is what provides dynamism.
View source and look for this:
StackExchange.init({...
Most server side languages make it trivial to serialize an object to JSON so you can inject it into your page.
Here's ten reasons utilizing external static js files is preferable:
Cached
Code colored
Syntax checked
Separation of concerns
Reusable
Easier to read.
One less layer of abstraction
Can serve minified and obfuscated
Avoids string parsing on every request
StackOverflow and all the cool kids are doing it (hey, I promised 10 reasons.)
More info here: http://www.bitnative.com/2013/10/06/javascript-configuration-object-pattern/

That depends on whether you want to generate files or return data. Generating files would be done with something like file_put_contents. Alternatively you could have a .js file in a folder with a .htaccess file that tells you to execute it as php, allowing you to simply generate the script on the fly based on session, get, or post parameters.

You can use any server-side language to create dynamic javascript files, javascript files don't need to end with .js. If you really want your files to end with .js you'll need to edit your server settings to also process .js files as for instance PHP files.
You can also use server code to generate inline javascript.
But be careful when generating javascript files, it can become very complex when you are mixing two programming languages

Related

Why simply use PHP variables for dynamic stylesheets?

I've been reading about dynamic stylesheets and have stumbled across several options, including sass, and less. But my question is why not just turn my stylesheet.css into stylesheet.css.php and simply use php variables. Then, I avoid all the dependency issues associated with all these other approaches.
Am I overlooking some serious problems by doing it this way?
There is the argument of code re-use: when writing PHP code to generate CSS, you're effectively duplicating (some) of the logic behind things such as sass and less. Why would you do that when there's a widely-used, tested and complete alternative available?
Another thing is performance. Standard CSS files are served by your web server with sane headers regarding caching by the browser. Your browser will not download that same CSS file each time, it just gets it from the browser-side buffer. By default, PHP is not cached at all (and you usually wouldn't want it to be). This means that, by default, your PHP-generated CSS would not be cached, incurring extra load on your server and extra waiting time for your client. While some of this can be solved (including sane header output in the PHP code that generates your CSS), some of it cannot (the overhead of the web server starting up PHP, for example).
Am I overlooking some serious problems by doing it this way?
I host all static assets on a CDN, which you should too. CDNs don't do PHP.
Also: caching, runtime performance, minification
PHP variables used in inline CSS code
Using PHP variables in CSS has many advantages, one of them is that you don't have to learn a new syntax. The use of PHP variables in CSS code is a known practice already implemented in many frameworks, themes, and other website-related scripts.
The most common use is in inline CSS. Here is an example of inline CSS making use of PHP variables:
<html>
<head>
<style>
.class {
color: <?php echo $text_color; ?>
}
</style>
</head>
<body>
</body>
</html>
This technique is usually used when the PHP variable represents a user setting set via an admin interface. One practical example would be in a WordPress Theme where the user can set the background or text color via the theme's backend.
PHP variables in an external CSS file
When it comes to external CSS files, it is also possible to use PHP variables, but in order to avoid PHP from parsing your CSS file each time it is retrieved, you would have to save the output to a static file like stylesheet-processed.css.
Both SASS and LESS need to be parsed before being saved to a ".css" file. The same goes for your PHP file, which you would execute and save the output to a static ".css" file, just like the other syntax.
Parsing CSS files is a very common practice and is widely used on many websites, and most well known websites. It is usually done to increase site's performance by minifying (~25% saving) the CSS code, combine multiples files into one (less HTTP requests), and gzip (~80% saving) the resulting files.
Here is an example of how you would use PHP variables in a file named stylesheet.php, and save the result to stylesheet.css:
<?php
// Get the parsed CSS code with the
$processed_CSS = file_get_contents('http://www.example.com/stylesheet.php')
// Save the processed CSS to a static CSS file
file_put_contents('stylesheet.css', $processed_CSS);
Put the above PHP code into a file named "parse-css.php" and access it through your web browser in order to create or update the resulting static CSS file.
And then in your HTML code you would include stylesheet.css instead of stylesheet.php.
You could improve your parser to make it minify the CSS code too, for example using the CSSMin PHP class.

include or call php or html file via .js

I have a js file that has the code for navigation for a site with ~600 pages..
Now I want to change the menu(colors, background, links etc) and I don't want to edit the JS file as the code here is like using images for the menu..so I was thinking that I will create a php file or html file and then call it inside that js file. Is this something possible?
Please advise.
You could have the js render an iframe instead of an img and pass along the url to the php/html.
You need to understand the difference between PHP, HTML and JS. They each occupy a different domain in web programming. PHP is for server side logic, HTML is a structural language and JS is an action-oriented language intended to function on top of the HTML that exists in the page (and may be rendered in JS).
All programmers have at one point tried to "hack" code like you are doing, by trying to find a band-aid fix to a complicated solution. It is not worth it. You will lose performance in the best of cases and either fail outright or lose browser compatibility and user interface quality the vast majority of the time.
In short, take your time and edit the JS. You can always do a find/replace on images to strip them out and insert CSS class declarations in their place. Do it right and you'll save yourself a big headache later on.

Get PDF output from XML generated by a PHP file and translated with an XSLT

I've used a couple of days to think of a best practice to generate a PDF, which end users can customize the layout for themselves. The PDF output needs to be saved on the server or sent back to the PHP file so the PHP file can save it, and the PHP file needs to know that it went OK.
I thought the best way to do this was to use XML, XSLT and Apache Cocoon. But I'm not sure if this is possible or if it's a good idea since I can't find any information of people doing anything similar. It cannot be an uncommon problem.
The idea came when I read about Cocoon converting XML through XSLT to PDF:
http://cocoon.apache.org/2.1/howto/howto-html-pdf-publishing.html
and being able to take in variables:
http://old.nabble.com/how-to-access-post-parameters-from-sitemap-td31478752.html
This is what I had in mind:
A php file gets called by a user, the php file generates a source XML file with a specific name
The php file then makes a request to Cocoon (on the same web server) to apply the user defined XSLT on the XML file. A parameter will be needed here to know which XSLT to apply.
The request is handled by the PHP file and then saved as a PDF on the server, and can later be mailed away.
Will this work at all? Is there a better way to handle this?
The core problem is that the users need to be able to customize the layout on the PDFs themselves, and I need the server to save the PDF and to mail it later on. The users will use it for order confirmations, invoices, etc. And I wouldn't like to hard code the layout for each user.
I've had some good results in the past by setting up JasperReports Server and creating reports using iReport Designer. They're both available in F/OSS ("community") editions, though you can pay for support and value-adds if you need those things.
This was a good solution for us, since we could access it via the Java API for our Java system, and via SOAP for our PHP system. The GUI designer made tweaking reports very easy for non-technical business staff too.
I use webkithtml2pdf to generate my PDF:s. Just create a document with HTML and CSS for printing like you would usually do, the run it through the converter.
It works great for generating things like invoices. You can use SVG for logos and illustrations, and they will look great in print since they are vector based. Even rounded corners with dotted outlines works perfectly.
A minor gotcha is that the input html must have th htm or html file name suffix, so you can't use the default tempfile functions.

Jquery functions. Should I hold it in one file or is it okay to intersperse it?

So, I have a lot of php files where I use jquery functions. Do I need to create a seperate .js file for all jquery functions or I can put it together with php files or it actually doesn't matter at all?
If you need a custom function on a page, I would leave that in the page. Anything your going to reuse between pages, should be in a global library function that you can include on all pages. Try to reuse as much as your code as you can in a library function.
Try to extract as much as your code into library functions. It's easier to maintain, and reduces code duplication.
If you are using a function in more than one places, then it is beneficial (more maintainable) to put it in an external file and include that wherever you need to.
Another advantage of keeping your Javascript external is that the browser can cache the files, even if it isn't caching the pages of your php application. By cutting down the page size you're making the site faster.
A downside of keeping Javascript external is that you can't embed php directives in the code itself. That can sometimes be a problem, though there are ways of arranging for your Javascript code to be able to "discover" things in the page.

How to save an XML file on server with Haxe PHP?

I am just starting out with Haxe development, and wanted to give the PHP side a go, but am already a little confused.
What is the best way to save some form data to XML files in a folder on a server with Haxe compiled to PHP?
Well you can do it two ways.
Make the website form in haxe, which includes:
making proper .htaccess file for the project on server,
writting a Main class (that htaccess will be pointing) which will take a request,
and return either a form html document or will take the data from the form...
then put that data into xml format,
and finally put that data into a file.
Here are Api files you should have a look at:
File methods for writting to a file
Web class that will get request data and fire up proper class and function, getURI, getMethod, getParams
Template class for generating simple html / very simple
Depending on complexity of xml you may want to use a specialized class
And the second way is almost the same, but you only compile to one file.
And in your html form, you put your action link to the php filed that came out of compilation...

Categories