I'm quite new to web developement and I'm working on a school project where I am to create a simple educational video platform. My upcomming task is to make my site a single page application. From what I've gathered, jQuery and AJAX will make this happen. While browsing examples and tutorials about these languages, I'm starting to wonder if my HTML/PHP/Script code structure needs to change. Picture contains the typical structure of my files.
I've been writing the PHP and HTML in the same .php file for each job the site has to do (e.g. upload video form data). I've included all of these in my main.php file. To make it a single page application, will I need to separate HTML and PHP from each include file, into different files? Also I'd like some feedback (opinions) on how I've structured this so far.
The high-level of what you want to do is move your php logic out of your html files. Here's how a single-page app should handle data flow:
In file.HTML: forms and fields take user input (anything from text to files)
In file.JS: You use jQuery to listen for events that are happening, essentially using your page's dom elements to pass dynamically entered data to your server through AJAX calls
In controller.php: The ajax call goes to a method in one of your controller files where all your logic will happen, items will be added to your database, etc.
In file.JS: The ajax call finishes by receiving data from your controller method, and makes the necessary changes to your view file (again using jQuery)
In file.html: The jQuery updates show a user the results of their input
The big change to make is separating your php and html files. Since you're doing a single-page application, you can probably get away with one html file, but you should have generally have a controller for every class (assuming you are using class and model interchangeably).
One thing that also might be missing is routes, though I've seen people getting by passing files as the 'url' field (a required field when making an AJAX call).
As far as file structure, most web frameworks will pair cs and js folders into a parent folder called public.
When it comes to jQuery, this is the best cheat sheet around. Make sure you have at least a basic understanding of the dom before going in too deep though.
You may want to learn about MVC pattern
you can start here
The MVC Pattern and PHP
Related
Here is the flow I would like to achieve:
I have a set of template .php files on server.
Visitor of the website chooses some options
Options are added to template files as pieces of code
Visitor downloads customized files (.zip should contain both default template files if not customised, and customized ones)
Original files remain intact for the next visitor
The flow is similar to bootstrap customisation, only difference is that on bootstrap visitors are editing .less files, and my visitors would edit .php files
I would appreciate if you could point me to general direction how to execute steps 3,4 and 5, baring in mind that user input will be stored in objects and arrays with javascript.
My php knowledge is very rudimentary, so I don't know where would I start.
If you need any clarifications please do not hesitate to ask.
Thanks!
If the users only modify configuration options it seems the best way forward would be to use JSON as it is very easy to encode/decode with JS & PHP with $.parseJSON (jQuery) and json_decode() & json_encode() respectively.
You would provide a form and then convert these user inputs into the JSON format and store it in a .json file which can then be zipped up and sent as a download to your user.
This would also allow users to upload their zip files and have the form inputs defaulted to their original options.
So lets run through how bootstrap does it.
Page to customize the bootstrap file, you would do the same with a similar form.
Once the form is POSTed, take the array of form inputs and validate them for malicious input, correct data types such as a number etc and remove any form inputs that should not be there.
Convert the input into JSON, without validation this is easy as json_encode($_POST).
Write that to a JSON file and allow the user to download it (zip it up if you want).
In your case you have multiple PHP files, this seems a bit off and you should not be using PHP files to hold this sort of variable configuration data, JSON seems a lot better suited.
Take a look at this SO question: What is the best file format for configuration file?
Three methods are mentioned, PHP's way, JSON & XML. Take your pick, but I'm willing to bet that the easiest one for you is JSON.
If you have not used JSON before, create a new PHP script and try out the functions with multi-dimensional arrays and have a play around.
PHP Documention for JSON
If you are using JavaScript to store user selections etc., I recommend you don't actually use php for any of the functionality you described. So do it like this:
Store templates as static text file with demarcated sections to insert user options. Make the demarcated sections different from php syntax like ###Your option here###.
This is easy.
Fetch the relevant template using AJAX and do a simple string replace in JavaScript on the demarcated sections.
Put the resulting php code into a <textarea> using JavaScript for them copy and paste into Notepad or something
Original files are static and code is client-side, so this is fine
So I understand you want to ship php scripts customised for the user.
Consider having php files that cater for all possible user inputs. Then capture the user options into a configuration file where the structure is predictacable and easy to create.
For example
# config.inc.php
# Created by script that captures user options
$config['allow_shipping'] = true;
then in the php script
# file1.php
include config.inc.php
if ($config[$config['allow_shipping'] === true) {
some_php_code;
}
Your steps will be
I have a set of .php scripts files on server.
Visitor of the website chooses some options
Options are sent to a server script which creates a config file.
Visitor downloads customized files (.zip should contain both script files and config file)
Original files remain intact for the next visitor (less the config file)
Some posts to guide you
How I can create installer for website. PHP mysql
and
PHP Installer Script
I would consider making default code snippets and have every "option" link to various required snippets. That way every time an option is selected it uses the right code.
To continue with #Crafter's example, you could have the following code snippets
if (
$config[
]
===
) {
}
I have done this once before when I tried something similar in Java, and even though it seems to be more work than it should, it will end up quite useful once you get a sizeable "database" of code snippets.
Hope it was of any use?
-Peter
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
I have a website with a jQuery UI navigation, and I've got ajax working to dynamically change content between html files. I'm basically just replacing the contents of certain div ids with the contents of other div ids.
This still requires numerous HTML files and I was wondering if there was a way to have a single html file and load content into the main page from it instead? What about an xml file?
Thanks for the tips and advice about best practices and possible solutions.
Using HTML:
Template Views-- Using this method you create separate html files for each piece of your site that you want to be able to load dynamically. This is More efficient, but it means you need to be able to manage your files properly.
Single View-- This method involves loading the entire page again, and extracting out the desired data in order to update the page. This is not very elegant or efficient, and I don't recommend it.
Using XML/JSON
This usually involves making ajax requests for data and using it to render the page on the client.
XML/JSON is typically more lightweight than html markup which decreases the amount of cpu time and bandwidth used on your server, however it does require that your users have computers that can handle doing some DOM manipulation.
This also requires that you have a good way of organizing your ajax modules. A pattern that I use looks like this.
$PROJ_DIR/ajax/{MODULENAME}.php
Then a module with the name calendar might accept an actions like, getYears, getTerms, setCurrTerm.
And within that script you switch thought the action to output the correct data, and or make the correct DB changes.
Multiple html files for views isn't a bad thing if you've structured it nicely.
I have an application using Jquery's UI Tabs for an overall menu, and they're great. However, I've come to a strategy question when implementing the new format.
First, the concept:
An index.php file includes several class files (also PHP) and calls the tabs
Each tab pulls in one file per page via the script's "ajax loading" feature (As described here)
Each tab's page contains a combination of static text, content loaded server-side at display, and content that's dynamically updated via jQuery's Ajax.
Now, the challenge:
Everything is working as expected except that pages that are pulled into the tabs don't have access to the aforementioned included php files on the index page. I'm able to use that content if I do a separate includes on each of the ajax included pages, but that could get out of hand in a hurry. So, I'm seeking a strategy to get one set of included files to persist across all my pages.
Any ideas for a graceful solution to this challenge?
PHP (well, the entire web) is stateless, meaning once the PHP interpreter has parsed a file, it spits it out and is done with it. There is no way for it to persist includes parsed in one instance to another instance.
The only way for the pages to gain access to files included in the "main" page is to include those files themselves. Like you said though, that could get out of hand and be pain-staking to maintain, which is why a lot of people resort to a registry file. Your registry file loads the includes you need, and you only need to include the registry file on all of your pages.
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...