I have a web application whose loading page presents a form with radioboxes for 3 types of input : Color, Size, Material. This loading page is basically a php file first.php that has 3 sections, a Header div, a Content div which presents the form and a footer div.
The action target for the Submit button is a 2nd file process.php which offers a page of choices. I want this file to exactly take up the space occupied by first.php - which is to say, I want the header and footer to stay as they are throughout the life of the
session. I could load the header and footer for every target php file but I'd rather save on the amount of content from server to browser.
What should I do to ensure that the 2nd(and every subsequent nth page) stays only in the content sub-section? The code for first.php is like this:
header comes here
<div id="content">
<form action="process.php" method="post">
.....
</form>
</div>
<div id="footer">
footer comes here
</div>
Thanks.
This is the method implemented by me: maybe not the best one, but the one giving me the best results without too many hassles.
make a framework page with all the HTML and some "holes" for the generated text, e.g. $header, $article, $footer and everything you have to change;
instead of a plain echo save the output into the variables above;
for every page include the framework as last line: include_once ('framework.inc'); and the "holes" will be filled.
BTW, I use also other variables for the CSS and Javascript specific to a certain page, for the <title> and other variable parts.
All the common php functions (session manipulation, DB management, etc.) are placed into another file, general.inc, included at the beginning of the page with include_once ('general.inc');.
If you want to hide those include files on your web server have their name starting with .ht, and Apache will not serve them.
I have read recently about dynamic loading content to just selected section by using JQuery Mobile lib: https://api.jquerymobile.com/pagecontainer/#method-load
Please check out engine descibed f.e. here: http://blog.stikki.me/2011/08/18/loading-dynamic-content-in-jquery-mobile-with-jquerys-load-function/
and of course remember about naming convention of jquery mobile sections.
IMHO it works quite good (;
Related
I have wrote my own CMS in PHP. It is quite simple, but it does not permit me to do some things, like the redirect with header() from dynamic page.
Here is its structure (very simplified):
<?php
$db = new PDO...
try {
//getting page info from database (by $_GET['id'])
//and put results into $pageInfo
$stmt->prepare
//.. catch etc...
?>
<!doctype html>
<html>
<head><title><?=$pageInfo['title'];?></title></head>
<body>
<?php
//this file below cannot contain a php redirect, because headers are already sent
include($pageInfo['content_path']);
?>
</body>
</html>
There is one page that is dynamic and can display other pages by changing the value of the get parameter id.
The included content often contains PHP scripts.
I have looked around the internet but I don't know how to resolve this issue.
May I create a header.html and a footer.html and include them into every page? But if I include the header file before including the content doesn't it send headers? How?
Really sorry if this question seems stupid, but I don't know how to do it. I haven't someone that teaches me, so I have to learn all by myself but for some things I don't know where to look.
Thanks in advance.
The preferred way is to have the application separated into several parts, one part that executes code (Controller or core) and another one that displays something (View or template).
For example in MVC (Model/View/Controller), your single page would be just a dispatcher that calls a controller, the controller executes PHP-code, and fetches some data by using the second part, the model, and finally calls a template to display the data.
In your example you could start by including two files for each call, one that contains only PHP-code and fetches all data, and after that one that contains a html-template with variables and only very simple code that is needed to display the data. You can then do redirects and exit in the php-part (controller).
You may remember that not long ago I asked you for some help with objects transfering through $_SESSION in PHP (more: Data loss during sending via $_SESSION from one script to another ). Currently I'm reworking the whole project and I don't have a foggiest idea how to do it properly. I mean, how to do it "according to the art", not "at any cost / the easiest (but nasty) way".
Here's the mockup of what I want to achieve (animated gif):
As you can see, I want my website to display at startup only the navigation, in which I want user to set his starting parameters. In the future, the navigation bar will have ability to be collapsed (to extend the data display section's height). When user sets the parameters (or not - for default view) and clicks "FILTER AND SORT" (which probably will be renamed to "GENERATE"), the second section should appear with data filtered and sorted as user defined.
Data is read from CSV file and stored in PHP Objects defined by my custom classes I've shown you in the question linked above. So I need to communicate data between 5 files:
FRONTEND:
index.php <-- my main file handling the website
FRONTEND-BACKEND:
navigation.php <-- file that shall be displayed in the navigation div
data.php <-- file that shall be displayed in the data section div / iframe (?)
popup.php <-- file that appears in a div over the index.php when certain DataBox is clicked; handled with tinybox2.
BACKEND:
classes.php <-- file with definitions of classes (properties and methods)
tinybox2 "library".
My communication flow is as to be:
navigation.php displayed on the top of index.php sends filtering and sorting parameters to data.php, making it appear on the bottom of index.php.
data.php and popup.php shall use classes contained in classes.php constructed from CSV file datafile.csv.
When a DataBox is clicked in data.php, popup.php appears over index.php content to display extended object data.
So, how should I do this, to make it properly? Which option will be best: $_POST, $_SESSION or maybe something else? Maybe due to embeeding all files in / over index.php it is possible to store all data in such a way, that no communication is needed? How to embeed files - with include, require or maybe other way?
There are lots of assisting questions, but still, the most important is: how to do it properly? Thank you for your help in advance :)
PS For certainty, please find below one additional usecases:
UC1: Standard use of display system
User enters website with the system
User chooses parameters for filtering and sorting
User starts generating view
Data is being read from *.csv file
During above, data is being filtered and sorted
Data is being displayed by the system to the user
Extensions:
5a. No data to display: system displays empty data section
6a. User want's to filter and sort again: back to step 2.
UC2 (OPTIONAL): User wants to share the data
UC1
User chooses an option to share data
System displays question if user wants to send it to printer, or e-mail
User chooses option (for this case: e-mail)
System asks for e-mail address
User provides e-mail address
System sends an e-mail with the current data.php data as it is displayed on website.
PPS I know I should show you some code snippets, but my current code is a mess with lots of interchanging html, php and comments, that cannot be cut of from the system (or would take me ages to clean it up to show it here). I'm asking you for help mostly, because I really want to remodel the current solution, therefore I'm rewriting the code from zero, using old one as a hint, not a template. Like Microsoft did with Windows Vista and Windows 7 :P Hope you'd understand ^^'
Okay, so here it is. The ultimate answer to a question some understands as too wide.
What was the case:
I wanted to achieve a two-section page, where the first (partent) section takes user input and uses it to filter the data in the second section. The problem was with providing parameters from the parent side to the invoked one.
What I had to change in my conception:
At first I thought about passing data with $_SESSION or other PHP way, BUT there is one major problem with such way of thinking:
As PHP is server side interpreted, it cannot dynamically add another page without refresh!
I know I didn't intent a new lightbulb or explore America, but it's still this conclusion what leaded me to accept the fact, that JavaScript usage is inevitable. I think most beginners will find this important: you need to completely change your way of thinking, as website ain't the same thing as traditional application. After this, it finally came to me (thanks to #Yoshi) that my initial problems with jQuery weren't a good reason to hold back from using it and I had to find out what they were.
Solution comes here:
Okay, so what is the solution?
I've started up with finding out what was wrong with my jQuery and... it was wrong way of interpreting "what is the scope of code included into php". If I include view/header.htm file into index.php that lays in the root directory, it will behave as it was in the root directory, not view directory. And that was the stupidest, as well as not uncommon error that one can make.
After finding this out (thank you #Yoshi again!):
I've created backend (model) for my app that can:
Read data from file
Put data into a class-based storage (that will in the future be then exported into a php file as "pseudo-database")
Then I've created a kind-of controller, that can use the model to pass data to a variable in my view.
At least I've created a view for my site, with the "parent site" (it has a backend part with a main-controller, and a frontend part with a view), and a "invoked site" that is opened through jQuery request, and contains a filtering backend and the main data view.
These 3 not-so-easy at first, but now so-so-essential, steps took me here. Please find some php-pseudocode below:
model_Data.php
<?php
// Class for single instance of data storage
model_DataSet.php
<?php
// Class for set of data instances storage
model_ReadData.php
<?php
// Code for reading CSV file with fgetcsv function
controller_DataMaster.php
<?php
require_once 'model_Data.php';
require_once 'model_DataSet.php';
require_once 'model_ReadData.php';
// Read data from file to a variable
$reader = new ReadData();
$reader->setConfiguration(//some setup);
$tmp_data = $reader->read("filename");
// Put data into the class
$dataSet = DataSet($tmp_data);
return $dataSet;
index.php (which is the main controller!)
<?php
header('Content-Type: text/html; charset="UTF-8"');
include 'view/header.htm';
header.htm contains HTML headers, includes of jQuery and jQuery-UI (for sake of datepicker) as well as css references, and (of course) physical header of the website with the input form displayed.
view.php
<?php
$import = include 'controller_DataMaster.php';
$usableData = $import->getAllDataSingles();
if (isset($_POST['data_from_the_form']))
{
// Do something!!!
}
?>
<table>
<tr>
<?php $i = 1; foreach($usableData as $singleData): ?>
<td><pre><?php print_r($singleData->getAllProperties()); ?></pre></td>
<?php if ($i++ % 3 == 0): ?>
</tr><tr>
<?php endif; ?>
<?php endforeach; ?>
</tr>
</table>
And this way you can achieve something that looks like this (currently - without any CSS applied):
So here it is. An easy, not very long, not very short answer to my own question. Case closed :)
Like for example, i have a page that has a form that asks the user to enter their name and last name and that form will be directed to a php file but at the same time, that page(form) has a mysql code because it shows the current names of the users that were recently added so will my file be saved as .php or .html?
Ideally, you would separate your server side scripting from your client side pages, calling them though either includes on an intermediary rendering php page, or ajax on a static html page.
a quick rule of thumb: If it has logic, interacts with backend resources or performs a calculative function, then it's php, if it provides structure to the output then it's html and if it provides blueprint for the presentation of the layout it's css.
Of course php!
if you are using php your pages must be in php otherwise your code will not get rendered.
you fill up the gaps using:
e.g: <span><?php echo $yourVariable; ?></span>
$yourVariable is either extracted from Database or has been defined
I have seen several sites where there is a form, starting with a dropdown box, and depending on the box chosen there is different form elements, for example, let's say I wanted to make an uploader script, the dropdown box might hold:
Upload
Delete
And is Upload is selected I would want a browse file element, while with Delete selcted maybe only the name should be imputted into a text field. How can I make it do so? I plan on using php for it and using the echo syntax to create the html for the forms, but is ther a way to have, for example an if statment, that changes the other form elements that show based on the option selected.
I have seen people use jQuery for it, but I can ONLY use PHP ad HTML for my project.
This isn't a direct solution but if you intend on carrying out this task exclusively with php/html then you should consider setting up a system such as this in the php file which serves the page.
<?php
/*Check to see if the user has submitted the form*/
if(isset($_POST['action']))
$action = $_POST['action'];
/*If no action has been sent from the client side, generate form*/
if(!isset($action)){ ?>
<form name="test" action="example.php" method="POST">
<select name="action">
<option value="update">Update</option>
<option value="delete">delete</option>
</select>
</form>
<?}
/* if update action, load file dialog*/
elseif($action == "update"){?>
<!-- relevant HTML or action for file load -->
<?}
/*Default to delete*/
else{?>
<!-- some action to place the input field -->
<input name="fileName" value="<? echo $FILE_NAME; ?>" />
<?}
?>
Essentially you're going to have to handle both page serving and form processing within the one page, using the value from the form select element to determine which blocks of HTML need to be loaded. Note that you will still have to provide a submit button for the form in order to trigger the action since there's no javascript events.
I want to distance myself from this solution as I know of it only through experiencing the Dunning Kruger effect and I'm sure the lack of client side involvement will be frowned upon by most.
You can't do what you want in purely server-side code without some sort of submission from the browser to trigger the check. PHP code runs on the server and returns the page to the browser. Once the page has left the server there's nothing PHP can do to it.
Sites I've seen that do this kind of thing on the server-side reload usually have an initial page where you choose the action you want, and then load the form for the chosen action. That's really all you can do without some kind of javascript on the client side.
If you can use javascript then you have many more options:
Trigger a reload of the form when the drop-down box is changed.
Send an ajax request when the drop-down box is changed and dynamically add the HTML returned by the server to the form.
Send fields for all options in the original page, and use the change event on the drop-down to show/hide the relevant fields.
Based on your comments to other answers there seems to be some confusion as to the role of javascript in the application. The server doesn't need to know about Javascript, or even JQuery. The server runs your PHP code to build the HTML for your page. The HTML can reference CSS stylesheets, images, Javascript files, etc, which, as far as the server is concerned, are just static files requested by the browser. Once the client browser gets the javascript file from the server it can execute it and enable whatever dynmiac page behaviour is intended. There is no Javascript code in your server-side application. The application is just a bunch of PHP files, with a collection of other static files to support the generated HTML.
Im no expert, but i guess since PHP is a Server-Side Scripting Language, there is no way to do this purely in php, other than to reload the page evertime you switch the dropdown option. Maybe you could accomplish it with frames (but who wants to use those?).
jQuery is just a pre-written javascript subset, are you not allowed to use javascript? if you can not use it, then your ability for dynamic pages diminishes greatly.
AJAX uses javascript as well and is the solution I use to load dynamic content. do you need examples or a way to do this without javascript.
I'm working on a web UI control called Folder - it basically mimics Windows Explorer folder - you see a grid of items inside a rectangle and can drag an item around, drop an item inside a different instance of the control, add new items and so on. each item is made of an item template - basically some php code that dictates the look of the item, for example an item template might look like this:
my_item_template.php:
<h3>my item</h3>
<p>i'm an item</p>
when dragging the item i want to replace it with a different template, for example:
my_item_drag_template.php:
<h3>my item</h3>
<p>i'm being dragged</p>
one page may host many different kinds of items, each with its template, its load template, its drop template and so on. my problem is moving all these templates from the server side to the client side.
what i'm doing now - in the server side stage i figure out all the templates that i'll need and include them on the page, hidden (display:none). whenever i need a template (for example when the user starts dragging an item and i need its drag template) i locate it, clone it and use. i'd like to avoid having all this code hidden in my page, maybe store it in a jquery's $(folder).data or something. however, i still need to move it from the php. one option would be to insert the templates to $(folder).data and remove them from the page on page load, but i'd rather avoid it (it adds unnecessary dom manipulation). are there any better ways?
It's certainly an interesting problem, but I don't think you are too far off from a good solution by storing the templates in the dom in a hidden div. Unless you have alot of templates, that generally is a great way to have easy access.
Another option is to ajax request a template when you need it. You can use jQuery's $.load function to get a chunk of html and inject it into an element.
$('<div class="newItem" />')
.load('getTemplate.php?template_id=newItem')
.appendTo('body');
You would obviously have to fill the new element with real data, but you can still do it in a single call.
There is obviously a performance hit by doing this, but the structural gain is pretty significant if you don't mind making the requests. It allows you to define your templates in your backend just like you would a normal page, instead of mucking them all together in a hidden div at the bottom.