randomise image only on "revisit" - php

Current Situation
I've currently got three divs. Let's call them LeftDiv, CenterDiv and RightDiv. LeftDiv and RightDiv both contain an image that randomises every time the page gets "reloaded", ie when you press F5, or visit a different page on my website. This is done using javascript.
Visiting different pages on my site is done with page IDs, like:
Homepage is website.com/index.php
About page is website.com/index.php?page=about
etc
etc
Visiting different pages basically only changes the content on my CenterDiv (which is obviously located in between the LeftDiv and the RightDiv). However, the background images also once again randomise. Which is probably because the page refreshes.
Desired Situation
What I basically want is those images to only randomise (again) when the visitor either refreshes or revisits the website all together (like entering the web-address in the browser again). What this most likely would require I believe is to not have the entire page refresh when a new page ID gets visisted, but rather only refresh the CenterDiv. So now we get to...
The Question
Is there a way to accomplish this? If so, how? What methods are recommended to use?
Thanks in advance for your help.

jQuery makes AJAX calls so much easier. Might want to check it out here
http://api.jquery.com/jQuery.ajax/
For your problem, I think something like this might work:
function changeDivContents(page)
{
$.ajax({
type: "GET",
data: "page="+page,
}
});
}
And then, in the link give an onclick= "changeDivContents('page_you_want_to_load')"

You need to change only content of your CenterDiv. This can be achieved with AJAX calls.
http://en.wikipedia.org/wiki/AJAX

Related

Reload Methods: Complete Ajax Solutions

My web application utilizes page reloads in places where the page structure changes.
For content changes initiated by the user it is all handled by Ajax.
However I'm planning on removing all the page reloads and replacing them with ajax calls that simply update the page using innerHTML for the body and head tags.
To do this I know have to manually call functions that are normally called by the onload event.
When I am done I will have a complete ajax application. My question is, is this standard practice now....I see a lot of applications where you do something and the whole page reloads, where even common elements are reloaded.
For example go to Apple.com and hit on the first button you see "Store"...you will see the whole page reload even the menu bar that does not change is reloaded wasting bandwidth..
Because I don't see other people using complete ajax solutions...I wonder if I am headed down a wrong path.
My question?
Is a complete ajax based web application best practice? (of course file uploads aren't supported, omitting this, is it best practice).
If so why do big sites not do it? I see few sites that actually employ ajax instead of page reloads.
There are a number of reasons not to go fully ajax. A few are:
If the user refreshes the page they'd be sent back to the home page;
if they pressed the back button, they'd go back to the previous site
they visited.
Search engines won't be able to index anything past the home page.
Anyone without javascript enabled or on IE 6 (or it's equivalent) wouldn't be able to use the site.
Lastly, it can be hell to debug a problem -- I went full ajax on a project a while ago and ended up regretting it.
If none of the above are important to your project, and you're looking to do something different, then by all means -- the real question you need to ask is "does the added complexity justify the savings in bandwidth?".
The concept of ajax is reload certain content of the page when you don't need to change all the content.
Your example of apple.com: it isn't a best practice to use ajax in navigation, because the history of browser don't handle this (use the back button of the browser and the navigation will not respond if you use ajax, keep that in mind).
If you have a box with testimonials and want them to change from time to time, so it's a good place to use ajax, avoiding the whole page to reload.
You can also have a static page with all testimonials to let search mecanisms to index that content.
Example of big sites? The search of google. When you type only the box of results is reloaded to view one preview.
So you have to choose when use and when not use ajax.

Print several different pages PHP

I want to have a button "Print all reports" which will print 5 different URLs at once. Is there a way to do it without making it redirect you to a new page I will have to create with all the code again for each of the URLs and window.print() it?
I think the way you have exposed is good from every angle. Have a different page which prints all code of 5 URLs and call window.print() function to open the print-dialog.
If not, you will have to use ajax to fetch the output of all 5 different URL's and dump it on the same page where the user clicked the button. But, I would oppose this approach since it loses the ability to go back to the page and user could be deceived if they bookmark it.
Well if that's what you want, you can AJAX content of all the five pages into one page and once it's all ready, you can print the single page. If you use jQuery, it will look like this :
(
function(){
$.ajax({url:"url1", success:function(resp){
$("#mydiv").html(resp);
//make other similar calls for rest of the pages
//and in your last callback, call window.print()
});
})();
Even if you don't want to use jQuery, you can do it with raw ajax.
using just a browser you write a script that generates 1 url out of 5 urls, and separate the html from each of the urls with this.
<DIV style="page-break-after:always"></DIV>
and then the user can just print out your 1 url and have 5 urls of information.

jQuery autocomplete - Hide php request page contents

I have an input field that autocompletes using text taken from a PHP page. It works well but is it possible to hide the text on the PHP page if it's accessed directly? I realize that the way it works it's as if the user actually visited that page but is there a trick that would allow that?
This should work, place it at the top of the page
if($_SERVER['HTTP_X_REQUESTED_WITH'] !='XMLHttpRequest'){
die();
}
jQuery automatically sends headers with AJAX reqeusts
No, you can't: as you say it's the user who's requesting the content (well, the user's browser), so the content must be accessible by the user, every "cloaking" technique can be easily defeated by a slightly skilled user.
The first trick I can think of is to use http headers.
On the code to load data for your autocomplete set a custom data that your php page reads to write his content otherwise you show nothing.
When a user try to access the page directly (put the url on the browser) it show nothing because browser do not put your custom header
$.ajax({
url: "data.php",
type: "GET",
dataType: "html",
headers: {custom:'showdata'},
success:function(){}
});
I use this trick to let my page knows what kind of content type to return because some times it should be json and other time it should be html
Obviously it's not perfect but many users won't see the data your trying to hide
Here's a simple way to make it a --little-- more well hidden. On the autocomplete data source page, check for a variable of any name you choose. For example:
if ($_GET['ninja'] != 'chop') {
return 'Sorry, this page is not directly accessible';
} else {
//data generated and returned here
}
Yes, it can be defeated. But take into consideration, "what's the point?" Are you storing mission critical data? Is it really not to be seen? This is the reason that many small websites contain horribly unsecure and XSS vulnerable code and yet never get hacked...it's just not worth it for a hacker to spend the time developing a custom hack to get to the data that's there. Hacking Windows, on the other hand, provides millions (billions?) of targets to do all sorts of nefarious things. I'm certainly not saying that your site's not important, but it doesn't seem like a case where triple redundant security is necessarily required.

counter for number of clicks on links in php

I need to implement a links-click counter, that will count the number of clicks on the link...
Right now what i am doing is, i am linking the href to redir.php, which will increase the counter in DB and then using header('Location:'); I am redirecting it to the correct URL.
This works but it is certainly not the best approach. In an effort to make my code efficient, how can I make this link counter better? AJAX?
Not much exp with ajax so I wondering how to do in ajax or is there any other better method...
I do not want someone to write a bot script that would make multiple requests to the redir.php and mess up the stats.
You can use
Javascript to make a Ajax call to your "counter.php"
Add a Javascript code (like Google Analytic) on each page to post on the database
Create a "cron job" to analyse the "access_log" (if you count the link in the same domain, server)
Add a PHP code to update the database when each page is generate.
But I think the first javascript method is the best one.
Add a class on the link to spy
Add a "Event handler" to create a AJAX post
Create a simple PHP script to update the database.
Aka
If you links are generated from a source like a CMS instead of by hand, you could pass the link ID to your URL and on the loading of the next page count increment that the link has been clicked. Going this way would require that you reload (without the link ID) the page after that step to make sure that someone copying the link would not make the counter increment needlessly.
This method is bulletproof if your user has javascript enabled, but if your user does have javascript enabled, you could still do the method stated above and through a client side layer, bypass the whole thing and send it through AJAX.
This might seems like redundancy, but this way, you accelerate your process for most of your visitors (without the redirect since you do it through AJAX) and in the case that the javascript doesn't work or is disabled, you have a fail proof system that would avoid missing any click
Building off of #Akarun's answer, here is sample code (in jQuery) for adding a "listener" onto link clicks with "spy" class. Note that I load an image instead of attempting a $.post or other AJAX event -- this is because those won't complete by the time the person navigates away from the page (which clicking on a link is bound to do in most cases), whereas the browser will get off a request for the image in time. It's still a normal PHP script, the browser just thinks it's loading an image.
$(document).ready(function() {
$('a.spy').mousedown(function(event) {
var page_url = "<?=$_SERVER['PHP_SELF']?>";
var target_url = $(this).attr('href');
if(target_url != "#" && target_url != "javascript:void(0);")
new Image().src= "/welcome/track_link/?page_url=" + escape(page_url) + "&target_url=" + escape(target_url);
return true;
});
});
Have you thought of mobile users and other devices?
I believe your first implementation is completely adequate and secure.
You completely control the counting and there is no issue of user manipulation.
It works predictably also.
After all, the ajax will just do the samething in counter.php; Read and update the database. Stay with your present implementation.
Do it the way Google does it:
Waterfront Rentals
A javascript function. The passed code aids security.
Actually looking at the Google source they load an image with the URL as a parameter
window.clk=function(e,b,a,k,i,c,j)
{
if(document.images) {
b=encodeURIComponent||escape;a=new Image;var f=window.google.cri++;window.google.crm[f]=a;a.onerror=a.onload=a.onabort=function() {
delete window.google.crm[f]
};
var d,g,h;if(google.v6) {
d=google.v6.src;g=google.v6.complete||google.v6s?2:1;h=(new Date).getTime()-google.v6t;delete google.v6
}if(c&&c.substring(0,6)!="&sig2=")c="&sig2="+c;a.src=["/url?sa=T&source=",google.sn,"&cd=",b(i),google.j&&google.j.pf?"&sqi=2":"","&ved=",b(j),e?"&url="+b(e.replace(/#.*/,
"")).replace(/\+/g,"%2B"):"","&ei=",google.kEI,d?"&v6u="+b(d)+"&v6s="+g+"&v6t="+h:"",c].join("")
}
return true
};

Ajax back button with dynamic content

I've created a page using JQuery and Ajax that helps a user filter through a series of options and ultimately displays a filtered list of products meeting their specification.
This all works fine.
The problem i'm having is the "Back Button" problem with Ajax, i know how to get around this with anchors on static content (i.e. Filter.php#Step2).
However, the page works by returning a list of product specifications, when a spec link is clicked, Ajax loads the same page again applying the links parameters, this is repeated up to six times, after which, the user is redirected to the filtered product URL.
If the user then clicks "Back", then of course, the filter page reloads from step 1 rather than the last step (step 6).
Does anyone know if this is even possible?
Every time you want to be able to go back to the previous step, change window.location.hash.
Ie.
window.location.hash = 'step1';
This changes the #foo part in the URL. You will also need a timer in JavaScript which checks if the hash was changed, as there is no way to reliably detect hitting the back button. Something along the lines of...
var oldHash = window.location.hash;
setInterval(function(){
if(window.location.hash != oldHash) {
//the hash was changed, do something
}
}, 50);
I hope this helps
I can't say I've implemented this before personally, but I remember the jQuery Tools tab component doing something similar. I'm not sure if it will work for your particular situation, but it may be worth looking at their approach as a starting point.
jQuery Tools AJAX:ed tabs with History support

Categories