I assume the answer is: "it is not possible because php is server language not client language", but I would like someone more expert than me to state this and eventually list all possible workarounds...
Question: is it (at all) possible to have a php function executed (only) when the user "clicks" or performs some other kind of action (e.g. mouse-over) in an html page without using any javascript?
(P.S. As a workaround I considered to access an intermediate page containing the php code to be executed when the client action occurs and then redirect as needed but this is not straightforward as far as passing the results of the php code goes.)
In general no. The only workaround regarding mouse-overs I can possibly think of would be a small 1x1 transparent background image that is generated by a PHP script and that is only shown if a user hovers over a certain element.
html:
<div id="mouseover_php">execute php</div>
css:
#mouseover_php:hover {
background-image:url(/path/to/php-script)
}
php:
<?php
// your code
// set http headers to correct content type and to disable caching
// output 1x1 pixel transparent image
But as all modern browsers use pre-fetching and caching (although this can be influenced by setting the Cache Control header) I certainly would not rely on this as an unquestionable indicator for a mouse-over event. So this would be, if anything, a very unclean hack.
Regarding clicks: Here the only possible way is to load an intermediate page, just as you proposed it. As far as I am concerned there is no way to achieve this without AJAX.
This is not possible without making a new request.
You must use a link to send the user to a new page (or the same page -- anything as long as a new request is made), or you must use something like AJAX.
There is actually one very hack-ish way I can think of. It's not exactly pretty, but it should work.
You could use an iframe as the target for a link. Basically instead of a link opening in the same or a new window, it would open in a hidden iframe.
Untested, but in theory:
<iframe name="testframe" id="testframe"></iframe>
Test
Edit: After some rough testing, it looks like chrome will not obey this. IE9 will to some extent though, it seems.
Related
The default behaviour of a web page is that the browser displays it "from the top". I can request it to be displayed from a specific bookmark if I set for example the id="my_bookmark" attribute to an element in the page and then request the URL mywebsite.com/mypage.html#my_bookmark.
I feel like there has to be a way to change this behaviour so that a page will automatically load at a specified bookmark further down the page, because that seems to me like a no-brainer, yet I can't find anything on that. Maybe I'm looking in the wrong places ?
Specific questions :
Is there a simple HTML5 way to do this ? Like some sort of <meta> tag or other that tells the browser at what bookmark to load a page by default ?
Failing that, I'm curious : how are bookmarks handled at all ? I feel like if they're included in the URL it has to be because the server does something with that information; can I do anything about the bookmarks with PHP ? Or even with the damned .htaccess file ?
If this feature doesn't exist anywhere, is there a good reason that I just don't see ? It does seem to me like it's a very straightforward thing.
If you're wondering, my use case is this : I'm making a web-based game that has the player move through a story by solving puzzles. Every so often the player discovers a new "bit" of the story (a couple of new paragraphs). When they do, they are taken to story.php where all the pieces of the story that they have so far discovered will be displayed, in reading order, from top to bottom. But I want the player to land on story.php directly at the last bit of the story that they discovered, and I want them to scroll up if they want to read the previous stuff. I feel like that has to be doable, and fairly simple.
The stuff I know : Some HTML5, some CSS, some PHP. I don't really want to use a specific new PHP library if it means I have to install it, and I feel like I want to avoid JavaScript, but maybe you can talk me into it.
If you already have the proper anchor tags in place, just point your links at story.php#anchor.
There's no way of identifiying these "Fragments" in PHP or telling the browser to scroll to a specific position from PHP, though. The Fragments are never sent to the webserver and only used internally by the Browser. And the position of the scrollbar is controlled by the browser based on the size of the content corresponding to the size of the Browser Window and screen resolution, neither of which is known to the server-side PHP code.
You can use the window.scrollTo function to scroll to a specific coordinate in your document. (See: https://developer.mozilla.org/de/docs/Web/API/Window/scrollTo)
I have a very large site and it takes pretty long time to load. It takes around 120 seconds. What I'm trying to do is loads 1st half of the site loads 1st. Then user can surf while others parts are being loaded.
What I'm trying to do is below.
1st of all is this possible ?
According to my knowledge Yes since Google PageSpeed does that. But the problem is if I use PageSpeed I would have to change my DNS server settings and etc. I would like to do this myself.
How can I get it done ?
What type of technology should I use ?
Given that pages have the .php extension and written in PHP language.
You can use the concept of lazy loading.
You can load only content that is necessary during the load then using jquery and ajax you can load the remaining content.
In this way user can surf and interact easily with the the part already loaded while the other part will be loading asynchronously.
jQuery ajax or post method can help you on this.
A simple example could be,
If There are 5 parts of contents in your page, 2 needs to be loaded immediately
The page will be loaded with 2 parts loaded, so it will take quite less time than 5 parts loading
After document is loaded you will use ajax to load the remaining 3 parts.
Ajax will send request to the specific page of your website(can be possibly named AjaxRequestHandler.php) with some parameters, and this page will process your request and generate html for this and will send it back to your main page which will just show this returned html and this all be happening asynchronously, so the user will be able to communicate with the initially loaded 2 parts
And even if you are new to web technologies, I suppose you have to have the knowledge of atleast ajax and asynchronous calls etc. to achieve lazy loading.
Edit :
For your this question
Except AJAX Is there way around for this?
I think you can try iframes if they can help.
Loading the main content in the page load without iframe while loading other contents in the iframes after pages is loaded.
This jsFiddle
jsfiddle.net/cGDuV/
can help you understand lazy loading with iframe, mentioned in this post of stackoverflow.
You can use javascript for the same if you want to avoid jquery.
You can manipulate the output buffer such that it flushes early thus achieving what your after in the screenshot you posted in your question.
http://www.stevesouders.com/blog/2013/01/31/http-archive-adding-flush/
You can lazyload all your images. Here's a jquery plugin that does it easily
http://www.appelsiini.net/projects/lazyload
You can combine all your js in one file. Same with your css files. This will help the speed.
You can incorporate caching, expires headers and gzip/deflate compression
https://github.com/h5bp/html5-boilerplate/blob/master/dist/.htaccess
I would suggest you load your 3rd party javascript widget garbage (Google+ buttons, fabebook like buttons, social, twitter stuff) in a non blocking asynchronous way so it does not slow down the page in the beginning.
http://css-tricks.com/thinking-async/
Optimize your images as much as possible.
http://kraken.io/
Use a CDN
http://www.maxcdn.com/
Finally test your site and see where is the big bottleneck and where you can improve the site for speed optimization. Use the waterfall chart feature
http://www.webpagetest.org/
One of the things you can do is to load all the essential (top half) of the page normally, then use javascript/ajax to load the second half of the page. This is a very common technique (and is often used to load images).
Here is an excellent tutorial from jQuery for Designers, walking through how to use jQuery to load images asynchronously after the page loads. http://jqueryfordesigners.com/image-loading/
Having said that, a two minute load time seems very excessive. Maybe you should check if there is anything that could be slowing down your server.
You need to determine why the site is loading slow. What is the size of the data you are sending? Google and Firefox have web developer tools to help you determine which elements are taking the longest too load. Once you've determined the culprit, try to load the worst offenders asynchronously.
Check out this article on aync requests: https://segment.io/blog/how-to-make-async-requests-in-php/
in my opinion you need an endless scrolling solution. That is, have a fixed amount of content per "page" (could be an estimated 1500px worth of height). Use jQuery to load another "page" when user scrolls down by a set amount.
If you really want to unconditionally load all the content, just use the same approach, and on document ready trigger the next page to load. The loop the page loader until the whole thing is loaded. That way, you load the first "page", and defer the content "below the fold" to subsequent requests.
What you want is what Facebook does Bigpipe and here is a relevant SO post: Facebook Bigpipe Technique Algorithm
There are other solutions involving all sorts of Javascript but since you want PHP and Facebook uses PHP you should read up on Bigpipe. Juho even has an example written in PHP so that should meet your PHP requirements (but yes it still requires js but not AJAX).
Prefetching Resources the web page require large files for loading can often benefited from changing the order that those files are requested from the server. Sometimes, it makes sense to download files before they are necessary, so that they are instantly available once requested. When the resources required for a page can be loaded in advance, the user-perceived network latency for that page can be significantly reduced or even eliminated. When you run Google pagespeed insights and see the result, you will see how the fix the problems in your website.
Some tips to load site faster:
Make fewer HTTP requests
Add a far-future expires header
Gzip your page's components
Minify your JavaScript, CSS and HTML
One more thing when loading a webpage and if you are using php with smarty you can use this plugin which reduces the number of http requests to you server and makes the site load faster by combining all the js and css resource's request into one single HTTP request.
Alternatively you might be looking for these plugins.
http://masonry.desandro.com/
http://isotope.metafizzy.co/
http://www.wookmark.com/jquery-plugin
Does all this stuff have to be on the same page? Does it make sense to split the content over multiple pages? Can some of it be delayed until the person requests it? Can it be grouped into tabs? Hidden tabs could be lazy loaded for instance.
Give serious thought to restructuring the content in other ways. You might be able to come up with an alternate arrangement that simplifies the problem.
Having in mind all that was mentioned above you may think of caching parts of your data/html code with memcache or in any other way possible so you skip its generation every time. Of course this depends pretty much on how often the data changes.
Don't browsers render the document as it comes in? Whatever you put at the top of the file will be received by the client first, and therefore will be displayed first. For example, when you try to view a very large image file online, it loads from top to bottom. The same is true for web pages. Just put the content you want to load first at the top of the page!
Answer to question one: yes
Answer to question two: above
Answer to question three: Nothing, just put the page in the correct order.
Well the idea is more or less the same as described by Pawan Nogariya above. You will need to fetch views and data asynchronously and then display these. But this means that you will never redirect or post back to any other page rather will get every view via ajaz. This will make you application SPA (Single Page Application) like Gmail. And, this will also mean you need to keep track of what has been renedered and what not, leaving you in a mess. So, instead of doing everything your way there are already developed and popular frameworks available that let you do that but they also make it SPA. Which means that your application doesnt "posts" to the server as in redirection but everything is doen using Ajax.
You can use Backbone (Backbone.js), Knockout (Knockout.js) and may others to achieve this. These are javascript based frameworks that help achieving what you have just asked and may expample and tutorials are also easily available. You can use it with any language as we are using it with C# (MVC) for a relatively large applicaiton.
this is going to be ugly! You should definitely consider using ajax calls to load page fragments AFTER a first content stage is loaded!
This is going to break almost all known web standards, but it might render the website in parts....
this being said: here's the ugly stuff
First: get rid of the <html> tag of your website, start with the <head> DO NOT use a <body> tag either.
Now send your html-code in the order you want it to be loaded (top first) using echo ...
after each closing tag of a group (say </table> or </div>) use flush(); ob_flush(); this will send all known content to the browser immediately.
The browser now decides if it can render the known content or not and if it will (based on the browser specifics and user settings) but with few exceptions it will.
some browsers like to wait for the closing body-tag that's why we dropped it, others even wait for the closing html tag (safari afair) that's why we dropped that too.
If you use the echo-flush scenario wisely you should be able to split the page into renderable parts which most browsers will display without an error.
Again... don't do it this way.. it's bad, ugly and not even near any web standards
But you asked for it.
For your this question
Except AJAX Is there way around for this?
I think you can try iframes if they can help.
Loading the main content in the page load without iframe while loading other contents in the iframes after pages is loaded.
This jsFiddle
jsfiddle.net/cGDuV/
can help you understand lazy loading with iframe, mentioned in this post of stackoverflow.
You can use javascript for the same if you want to avoid jquery.
With pure PHP? Not smart.
$(function() {
$('#body').delay(1).fadeOut();
});
Fiddle example: http://jsfiddle.net/r7MgY/
fairly simple question and I haven't seen anything asked with this exact scenario laid out.
I have a form on a page. "Page 1"
The form's action is calling a PHP document, and the target is set to _blank. "Page 2"
The PHP document processes the information, then sets the header info to a specific page. "Action 1"
I would like for "Action 1" to instead open multiple pages; I know of several ways to do this via javascript, however, I would like to stay entirely within the PHP file if at all possible.
As php is a server-side language and HTTP has (thankfully) no way of redirecting to multiple URLs, you'll need to implement your feature in JavaScript. Note that this is extremely likely to fail on mobile and exotic user agents, and it's a hassle to users in any case.
There is a way to open multiple pages, however it's not really nice. You can do that with frames and always leaving one frame as the next target which will be a new frameset leaving one frame as the next target and so on.
Done that you can continue to open new frames - until the last one is about the size less a pixel on the target screen. This does only work if the browser still supports frames.
I have recently been debating whether or not to use AJAX for my site navigation to only transfer over only needed updated HTML elements, or if there was not a significant difference between new elements and current elements to just load the page in its entirety (php generated or static html)
However, I thought how that if the new content was not large in size relative the current page...that perhaps I should send it has a hidden div (via CSS) along with the current page.
This 3rd way seems like a simple solution. For example just send the entire current page + any additional content that might be requested by the user as hidden divs.
When the user selects the content just hide the current content, and display the hidden content...
All in all, each way (normal, Ajax, CSS) would look the same to the user but a CSS / Javascript solution would be provide the quickest interface and be the simplest. Ajax might cut down on download for example if the content is never used.
This is a validation question. Is this a valid way to navigate a web application? By hiding/displaying divs using the display property or opacity property to flip through content?
Notes (response to answers)
The Hidden divs would be static data that is not changed by the user. I thought this would be obvious but now I've made it explicit.
Thanks!
You need to think about it this way.
If the hidden content is dynamic (changing) there is a need for AJAX because AJAX would usually be used to fetch updated content from the DB.
If your content is static (not changing) then how much new content are we talking? Does the size of the new content have a significant impact on render time if it was in a hidden DIV? If its very little, then I would say use a hidden DIV. If its alot, then mabye it's time to consider AJAX to load it in from an external page.
Here is a simple solution to get you started using a hidden DIV:
<script>
function setVisibility(id, visibility){
document.getElementById(id).style.display=visibility;}
</script>
<div id="message1" onclick="setVisibility('message1', 'none');setVisibility('message2', 'inline');"> >Hey What's Up?</div>
<div style="display:none;" id="message2">Not Much You?</div>
It does depend on the data being shown. Facebook could not do this because the data is updated often, there would be out of sync problems.
Since i do most of the development by myself, having a full ajaxy site seems like a large task for me, so i usually keep page flips, but some of the content on the inside i have it as ajax generated.
Like say there is a form to create something, i have that form submit in the background (excellent jquery plugin for that) then i have the new data be displayed at the top of the list ($.prepend). This way, things are still ajaxed, but not to a level of which is hard to manage for a single programmer.
One thing you need to keep in mind is to keep your site as non-breakable and accessible as possible. Because Ajax content isn't on the page, it can't be indexed by spiders, etc. Ajax requires more error testing/catching, etc than "standard" CSS alteration, so make sure you're going to make it work in ALL browsers. There's no excuse for bad or broken navigation.
Your idea is definitely a valid approach. You're basically looking for a trade-off between an initial, longer request, and many shorter ones down the line. As long as the amount of initially hidden content is not gratuitous, the user experience will likely benefit by getting all of the markup first, and hiding/showing it with JavaScript + CSS as needed.
Suggested Approach: Consider using jQuery's
hide()
show()
or toggle()
methods, and combining with a history manager to emulate real browser history changes as the user navigate's page states. This is the approach I use on my website: paislee.net. IMO its clean and lightning fast because there are no new HTTP requests.
I was recently visiting a site and noticed that the page had a section that said it noticed that I was using AdBlocking software and could I kindly turn it off to help support a small site like that.
I was just wondering how you would do that? Would it be best done client-side or server-side?
This is something that simply can't be done server side - there's zilch reason for person to knock on your door and say "Look at me, I have AdblockPlus!". When on the client side, adblock is actively trying to influence the page content, which is something you can see happen and see that they are using an adblocker.
Anyway, I happened to know that newgrounds.com is doing this too. (their new layout was screwed up for adblock plus users - as a response they made a contest for the best "if you're not going to help us through our ads, go and buy something in the store"-banner.
A quick look in the source of newgrounds told me they are doing this with some simple javascript.
First in the document:
var user_is_leecher = true;
Next there is a external script tag: src=checkabp?thisistotrickabp=***adress of ad affilliate***
Now the joke: they simply trust adblock plus to filter that script out, as all that's in there is: user_is_leecher = false;
From there, they can do just about anything.
All off the methods mentioned here rely on the ad blockers to strip out code. This doesn't work for some adblockers(like NetBarrier on Mac). You also have to keep updating your code when the adblockers catch on.
To detect if the user is blocking ads, all you have to do is find a function in the ad javascript and try testing for it. It doesn't matter what method they're using to block the ad. Here's what it looks like for Google Adsense ads:
if(typeof(window.google_render_ad)=="undefined")
{
//They're blocking ads, do something else.
}
This method is outlined here: http://www.metamorphosite.com/detect-web-popup-blocker-software-adblock-spam
You could do it on server side by pairing requests for html pages and for the acording ads (probably with some unique identifiers to each request ...) ... But this is just an idea, i've never tried it and never even seen it used.
I found this part in the code which seems to look like how they did it:
/*MOOTOOLS*/
window.addEvent('domready', function(){
$$('.cat-item').each(function(el) {
var fx = new Fx.Morph(el,{ duration:300, link:'cancel' });
el.addEvents({
'mouseenter': function() { fx.start({ 'padding-left': 25 }); },
'mouseleave': function() { fx.start({ 'padding-left': 15 }); }
});
});
if ($$(".google-sense468")[0] && $$(".google-sense468")[0].clientHeight == 0 && $('block-warning')) $('block-warning').setStyle('display','block');
});
/*MOOTOOLS END*/
I guess there are several ways of doing it, but probably the easiest one would be to have some kind of background image, or text, that will be replaced when the ad is loaded. Thus, if the ad gets loaded, you see the ad. If the ad doesn't load, you see the text.
This example would be client side, done by either JavaScript or just plain CSS might even suffice.
There might be some server-side gimmicks that could do this too, but they would be unnecessarily elaborate and clunky. One method that springs to mind would include some kind of API with the advertiser that could be asked "did the user from IP such.and.such load any images?" and in that way get the answer. But I doubt there's such services - it would be much easier to do on the client side.
I believe that is much easier to do it on client side than in server side. Ad blockers are installed on the client, so they can manipulate DOM and block ajax requests. That's why I believe it makes more sense to detect on the client than on the server.
Anyway, this is a standalone simple plugin that detects users with ad blockers enabled, it's open-source and the full code is on github:
https://github.com/retargetly/mockingbird
It's more publisher oriented so they can easily show messages on the ads containers or in a popup. The plugin is frequently updated, and it's worth a try. This is the fiddle also:
http://jsfiddle.net/retargetly/9vsha32h/
The only method you need to use is
mockingbird.adsBlocked(Obj)
The call can be done anywhere in the code and you don't need jQuery to make it work.
Wish you luck !
I don't think there is an easy way to do this. What you can do is to create "trap". Make a php script listen to a very obvious url like yourdomain.com/ad.png. You can probably achieve this by url rewriting. If this page is loaded you can note this in a session variable and send back a 1x1 blank png.
On the next request you can see whether ad.png has been loaded. If it hasn't you can guess that the client is using some form of AdBlock software. Make sure you set the appropriate http headers to prevent clients from caching "ad.png".
This is the only server side approach I can think of at the moment and it has some flaws.
The png file can be cached regardless of the http headers
This will not work for the first http request
Some extra server load as browsers will keep hitting ad.png for each request
That the image gets loaded from the server is no guarantee for it actually being displayed
Probably more side effects that I haven't thought of
Please make a comment on this post if you decide to try it out.
Regarding a client side solution. This shouldn't be to difficult. You can create a tiny Javascript to run on page load complete. This script can check that the page contains the dom-nodes holding the ads. If you this when the page is loaded completely (not only the dom) you can check the width and height of your ad images. The most obvious drawback with this solution is that clients can disable javascripts.
A few good answers here, so I'll just add this:
use some ad management system (You can write Your own). With that, track every ad that's being displayed (and make it obvious, like ads.php or showad.php or whatever). If that script is never called, the user is using SOME form of ad blocking software.
Be sure to handle each and every ad through that handler, though. Mod_Rewrite isn't required, it can be done using simple PHP.
What you can do to detect the adblocker on the server-side is somithing like:
<?php
header('Content-Type: application/javascript');
//Save it to session
session_start();
$_SESSION['noAdblocker']=true;
?>
noAdblocker=true;
Save this file as ads.php
Now the index.php:
<?php
session_start();
$_SESSION['noAdblocker']=false;
?>
<!DOCTYPE HTML><html><head>
<!-- Now place the "ad-script" -->
<script src="ads.php"></script>
</head><body></body></html>
You can add javascript-code to your page, that is only executed if there's no adblocker, e.g. use "ad" as variable-name, use "ad.js" as file-name.
This code sends an ajax-event to the server, saying "this user doesn't use an adlocker". So if you don't receive that event, you know, that this user is blocking ads or even javascript altogether.