Dynamic php pages - php

I have a header and a main div on my site. How can I create dynamic pages without refreshing the page, by just placing the files from profile.php, search.php and so on inside the main div of my website through using navigation menu?
For example, I have profile.php as the users main interface, and using ?action=action I have achieved the dynamic pages. But when it comes to search, I have to redirect the user to search.php?query=search-text and so on for the other pages.
Thanks.

Sounds like you want to do content replacement using AJAX.

Using JQuery you can do
$('#divid').load( "URL" )
Using Javascript and Frames are the only ways to do this without refreshing the header. Frames are considered bad pracice, so AJAX and JQuery are your best option here.

There are several ways to do this.
If you are not using a framework (it looks like you are not) you can just use include/require to bring whole chunks of code into your file (requires a page refresh).
If you are using a framework that supports the MVC structure, then you will just include multiple views to build your response page. The syntax differs between different frameworks, so sorry no example code for you (requires a page refresh).
Also you could use AJAX. Note, AJAX is not a new programming language. It is using Javascript to execute an independent call on the end-user's browser to your server at a special page/handler. The server side handler script then processes your request and returns a snippet of HTML code or a small block of text which is then received by your end-users browser and then dynamically inserted into the DOM (no page refresh).
Cheers.

The only way I know how to achieve this would be requesting content with AJAX and setting the content of your div to being the result - might not be the most ideal (not sure as I've never looked into it) but that's how I would go about it. JQuery would make this easy like so:
function loadPage(pg)
{
var container = $("#container");
$.ajax({
method: "post",
data: "page="+pg,
url: "loadhtml.php",
success: function(result)
{
container.html(result);
}
});
}

Related

How do I preload .css and .js files, before the whole page (dynamic by PHP) is generated

My homepage (index.php) is generated dynamicly by PHP, so it takes about 1s till the the page is delivered to the user.
Because my css and js script is in the header of (index.php), after this 1s the css and js will start to download.
Is there some general way of preloading this js and css files?
My aproach would be to delete all content of index.php, include just <'head> with my css and js file, and then do some js to load the whole indexOriginal.php (with the dynamic content generated on my server by PHP), so this should enable the user to download the css, js in parallel of indexOriginal.php.
Is this the right aproach?
The approach you suggested could work. You also might consider altering your PHP script to hurriedly deliver the first part of the page (<html> down through <body>) before it starts getting the rest of the page together (see http://php.net/manual/en/function.flush.php).
Your page full generated by backend and sended to user only after php script end its work.
You could, for example, create page like.
<html><head><script></script></head><body></body></html>
In <script></script> load, for example, JQuery and do something like
$(document).ready($('body').load('/path/to/your/script.php'))
But I really thing this wouldn't be a good practice. Also I don't think that Google would parse your site content with this solution.
I think you should look better about your JS (compress, gzip, split to many files and upload them from different CDNs, move everything to $().ready, etc.)
My recommendation would be to have your initial PHP script JUST deliver the CSS and JS tags. Once those are loaded, use the JavaScript to make an AJAX call that gets the rest of the page then displays it. Or you can build the page in the JavaScript (which would allow you to use loading icons and the like to give a better indicator to the user that "the page is coming")

Including php to another php and keeping included?

I'm looking for a solution similar to the php include method, except like at html's iframe tag, if I click a hyperlink on the included php, I don't want the browser to navigate the whole tab to the new url, but only navigating the included page without getting the parent page change/disappear.
UPDATE:
okay, thanks for the quick answers, seems like I didn't ask the right question:) so here is some background info: the whole page itself is a single-file website using the exactly same javascript+hiddendivs page changing method than that you just wrote. my problem is: I'm using a flat-file CMS to keep my News page managable by people having no coding knowledge. so I made an own template for the CMS only showing the news themselves. Then I embedded the CMS's index.php to my parent index.php with php include method and it looks really well, except my problem is, when I click "earlier posts", it navigates to the CMS's index.php and loads earlier news in there. I'd like it to load earlier news without navigating anywhere, just like at html's iframe method. (I will use iframe if there is no other solution, but its configuration would be really complicated if I wanted to stay cross-browser supportive)
From the action described it sounds like what you're looking for is not actually PHP but client side JavaScript. AJAX can perform exactly what you describe and there's a very easy library called jQuery to help you do this, with minimal effort.
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.ajax/
You can bind your button to a JavaScript function which can then fire AJAX, grab the result of your other PHP page and display to the user in a .class or #id in the HTML, without leaving the current page.
If the behaviour your looking for is more advanced and "app like" you can also consider entire MVC JavaScript frameworks such as Backbone.js or Ember.js
The best thing you could possibly do is use jquery/javascript and manipulate a div (or the iframe) to where it navigates to X link when interacted with. You can actually change the url of an iframe using jquery and have it re-load to any url that you want. Reload an iframe with jQuery is a good example of how to do that. And for interacting with and digging through the contents of an iframe, instead of just changing the attributes of it, take a look at http://developer.vimeo.com/player/js-api.
Do keep in mind that the 2nd link is for a media player, BUT it still shows (and in a very simple way) how to interact well with iframes. You could use jquery to insert an id or class to the links in the page originally loaded into the iframe, then have the script on the 'parent page' navigate the iframe to one of the links when it's clicked. Just toy around with it some and have fun with it; a learning experience doesn't always have to be like a personal hell. I'll check back later and see how things turn out!
To do this you must understand what you are dealing with.
The *.php page loaded into user's browser is a processed and parsed page.
This parsing occurs at the server-side, and processed by the PHP processor on the server.
Now, after a *.php file is processed any interaction with it is lost. The only thing a user (client-side) sees is the result of this processing. Hence, to communicate with this page an information must be sent.
Normally, browsers send information on requesting a page. That is how the HTTP protocol works.
Since the user is the client-side, he must send relevant information (headers, variables, etc.) by the rules of the protocol. This means, a user must request the page and by this request the data will be sent.
AJAX technology allows you to open an HTTP request dynamically, on the background, while the page is still running with no need to refresh. It sends the relevant data according to protocol's convention and allows you to trigger a callback function to handle the answer when it arrives from the server.
Here you can find a beginner's tutorial, that will provide the necessary information for you to start.
P.S.
I would strongly recommend you not to use common external libraries like jQuery, node.js, Backbone.js etc. at the beginning. These libraries are tools that were created to simplify code writing for advanced developers. They may confuse you and mess up your programming logic and learning path.
Good luck!
Sounds like you want new content to appear on the page, without the user being directed to a new page. You can achieve this with jQuery. This is a quick example.
HTML:
<p>
Page 1 Page 2 Page 3
</p>
<div>
<div id="content1">
This is page 1.
</div>
<div id="content2">
This is page 2.
</div>
<div id="content3">
This is page 3.
</div>
</div>
jQuery:
$('#content2, #content3').hide();
$('a').click(function() {
var id = $(this).attr('id');
$('#content' + id).show().siblings().hide();
});
Live Example: http://jsfiddle.net/VxZKs/1

How do they do it? Dynamic Loading pages/websites ... Framework, script? PHP, jQuery, Ruby?

So I'm sure a bunch of you have seen or even use sites that load pages seemingly dynamically, without ever actually changing pages. As well as changing the url in the address bar.
Some great examples are reverbnation.com and rdio.com, I'm sure there are more where that came from but that's just off the top of my head.
So my question is... How do they do it? What coding language are they using? is it a combination of languages. Do you know any tutorials that may be helpful.
I think it maybe a combination of ajax, jquery, and php. Possibly utilizing iFrames? But i was just curious if there was a framework or jquery plugin that Im missing.
Thanks ahead of time for any help.
I quick review of their code learns that http://www.reverbnation.com/ is using a lot of javascript to get that working.
Basically you need:
- A database backend, which can be
MySQL.
- A markup language for the presentation, lets say HTML
- A programming language like PHP to do the logic
What you are asking is about AJAX, which means asynchronous JavaScript.
Here you have a good sources to learn the basics of AJAX:
http://www.w3schools.com/Ajax/ajax_intro.asp
I can see a very complex way to do this by using the server to create content for you an getting it to the page in bits ore as a whole block.
I started trying this out the other day for a very simple client project, just creating something simple. There reson I'm doing it this way is to be able to create animation to change content.
This is my idea;
var href = window.location.href;
This will get the whole href from the address bar.
href = href.split("#/");
this can also bee # to split from an
has tag
item = href[1].split("/");
this can be anything you like to use to split each paremeter item.
lastitem = item[item.length-1]
This will add the last item of the array to an var. At this time its the only thing I need to find the correct page with the content I want.
This way I have the link in two parts, the first is the href after the hash tag, the last one, the "item", is each end link.
So there is just one index file, everything else is added into the content area with an jquery ajax url. At the start I check what the link is and find. Each content is just in another php file. But jquery can just as well get an html file an add its content anywhere you want with ajax url.
When the document is ready I check what the last item in the parameter (after /) is. I then have a php file with the same name, I find it and add it the the content area.
$.ajax({
url: lastitem'.php',
success: function(data) {
$('.content').html(data);
}
});
The links will then use a jquery .click(). If there is a site called "about" the the href of that link can be About us . This will then ofcorse add this to the end of the url in the address bar.
The click event can than be like this
$("a").click(function() {
var href = $(this).attr(href);
href = href.split(#/);
href = href[href.length-1];
$.ajax({
url: href'.php',
success: function(data) {
$('.content').html(data);
}
});
});
This is just a quick simple idea that I'm going to try out.
The general category of such solutions is called "ajax".
The idea is that you don't close the connection to the web server after asking for some data, and the web server pushes replacement "portions of the web page". Depending on how fancy you get, those replacement items are listened for by the non-replaced portion of the web page and processed accordingly by either the web browser (simple html changes) or the javascript engine in the web browser (code triggered on replacement).
This technique can be done in any language on the web server side, but it must be done in javascript on the web client side. That is because javascript is the only language guaranteed to be built into every modern web browser.
While simplistic, this resource should get you started.
Question answered already: Change browser URL and page content without reload and without using fragments
Dont be misleaded, because a javascript framework is made using javascript, meaning anything can be done using only vanilla js.
In my experience, it can be possible that when a script is loaded the whole rendered view will also change, this is because it is possible to create HTML markup using javascript inside javascript file.
let's say in script1.js you have a markup like
let template = `<div>Loaded in script1</div>`
document.body.innerHTML = template;
in script2.js
let template = `<div>Loaded in script2</div>`
document.body.innerHTML = template;
as you can see, when either of the two script file is loaded the must be unload, if so, the rendered view will change dynamically depending on the loaded script.

PHP: how to determine if the browser supports javascript in PHP?

I am building an AJAX deep-linked site.
I want PHP to load all the HTML code of the page if the user is trying to access the site with a Javascript non-supported browser or if it is a search crawler. Basically PHP will return the whole page.
On the contrary, when the user is trying to access the site with Javascript supported browser, I want PHP to return only the template code, and let Javascript (AJAX) take care of the rest. Basically PHP will only load design elements and let Javascript populate them with content.
I looked into PHP's get_browser() function, however it seems it is not such a reliable tool. What is the industry's practice see if the browser supports Javascript or it is a search crawler using PHP?
Background:
Why I want the site to have this behavior.
Since I want the home page to load just by loading the address: example.com, which does not send any query to PHP, PHP returns the HTML code of the home page. This however causes issues when the user tries to load the following page: example.com#foo. So, for this example, PHP will return the home page and once the home page is loaded, Javascript (AJAX) will change the content around so that it shows proper content for #foo. This will make the user to see the home page, therefore load time will be slower and user-experience will not be so nice. However if my PHP script can figure out that if the use with Javascript supported browser is trying to load the page, it will only return the template of the web site, which has no content) and the javascript will populate that template with content whatever is supposed to be displayed for #foo. On the other hand, if the Javascript non-separated browser or a crawler will try to access the page example.com#foo, home page will be returned.
I am using SWFaddress (http://www.asual.com/swfaddress/) library for the deep-linking.
Edit
Thank you guys. I did not think of using <noscript></noscript> before.
Here is what I decided to do. PHP by default will load pages such as example.com or example.com#foo (which is essentially the same as example.com from PHP's point of view since fragments by definition are not sent to the server) blank (just visual template) with <noscript> tag inside for the content of the home page. This way users with javascript will not see the home page and AJAX will populate the content of the page according to the #foo fragment. On the other hand, search crawlers and users without javascript will see a home page.
Thank you again. I think this is pretty simple and elegant solution. If you have any further suggestions, please post a comment or another answer.
You can't do this using PHP. What you can do though is use a noscript tag to redirect to another php page if they don't have javascript:
<noscript>
<meta http-equiv="refresh" content="0; URL=nojavascript.php">
</noscript>
It's not possible to accomplish this in the way you're trying to do it.
It's rare that someone has JS turned off and doesn't know it.
PHP doesn't get passed anything after #, only javascript can do anything with that. So even if PHP could determine if the browser has javascript turned on then it still couldn't read # anyways.
You could include a link inside some <NOSCRIPT> tags that point the user to something like example.com#foo?javascript=disabled.
Unfortunately, browsers do not report whether JS is enabled or not, so there's no way to know from a simple HTTP GET whether or not you should send JS reliant pages.
You should just build an AJAX query that sets a session variable for javascript enabled.
Run this AJAX query before any other information on the site is loaded and then do a simple redirect to the actual site.
You could do something like this pseudo code:
Index.php:
ajax(check_js.php);
redirect(main_page.php);
check_js.php
$_SESSION['js_enable'] = true;
main_page.php
if($_SESSION['js_enable'] == true) {
//execute page
} else {
header("Location: no_js_error.php");
}
Instead of the server trying to sniff our the user's settings, how about using unobtrusive javascript in the first place? This way, the page will degrade gracefully (to the desired state) if JS is not available.

Why not just using ajax for Page Requests to load the page content?

Many web pages load all of their content to change very little information.
Now I would like to know why shouldn't the developers just use ajax for the main page requests?
On my own webpage, I would like to develop the main requests on my webpage with just ajax but I don't know any specific cons with this approach.
Does anybody have an idea why someone shouldn't use ajax so much?
Search engines, crawlers/spiders, browsers with no javascript, screen readers and other consumers of the content will not be very happy with it.
You can provide tons of ajax behavior on top of you website if you already support standard server side navigation for the full content. Have a look at progressive enhancement (SO) and progressive enhancement (wiki).
The whole premise really is that with AJAX you don't need to reload the whole page to update a small percentage of that webpage. This saves bandwidth and is usually much quicker than reloading the whole page.
But if you are using AJAX to load the whole page this is in fact counterproductive. You have to write customised routines to deal with the callback of the AJAX data. Its a whole lot of extra work for little to no increase in performance.
General rule for where to use AJAX: If your updating >50% of your page, just reload, else use AJAX.
I'll give you one very good reason.
If you turn off javascript in the browser it won't work.
The biggest con are users who have JavaScript disabled. Your website simply won't work for them.
Aside from the answers already posted, using AJAX can have ugly side effects on browser control, such as the stop button not working.
One thing is that you want content to have a static url, you want people to be able to link to your pages, bookmark them, etc.
If everything is ajaxified, this could be tricky and/or tedious.
Well if you want to AJAX load new pages, such as the same way Gmail works, I suggest your links are normal A HREF links that point to a true full rendering page URL and alos use an onclick event that stop the attempt at normal link loading and make your AJAX calls. The problem here is you'll be doing almost double coding unless you architecture this all very well.
This way the normal non JS links load the full page, and the JS calls only load the new parts or page. This means spider indexing works again too.
Well, you can always add the onclick event unobtrusively using jquery and stop the normal URL handling.
Eg:
HTML
<a id="ajaxify-this" href="my-working-url">Click me to do AJAXy stuff if you have javascript</a>
then Javascript
$(document).ready(function() {
$("#ajaxify-this").click( function(e) {
updateContent(); // do something ajaxy with the page
return false; // stop the click from causing navigation
})
}
I use only JavaScript and EJS as template Engine for my own webside. One step closer to SOFEA/SOUI.
Search engines, crawlers/spiders, browsers with no javascript, screen readers dislike it, right. But I follow the mainstream ;)

Categories