AJAX Php ensure page loaded in framework SOLUTION; same using LightWindow; Ajax.Updater OR Ajax.Request ALSO handy $_SERVER['REQUEST_METHOD']=="GET" trick

Wow, I tried a MILLION solutions to this,
and some of them worked...almost...perfectly...
and along the way I learned A LOT,
including some awesome JavaScript and PHP logic, URL sniffers, decision makers, GLOBALS, and so on...
but now, of course, the TRUE solution,
and duh, of course, it's SIMPLE, the SIMPLEST

Scenario, AJAX framework,
loads external pages into a div in the framework,
we don't want said external pages loaded by themselves, that is, their URLs should be visit-able...

Solution:
when AJAX function that loads an external page calls for it,
it also submits with its request a form, or a variable, to the page being loaded in,
page being called looks for that variable,
and without it, follows another line of action,
DUH!

example using Prototype AJAX functions:

AJAX.Updater Version:
button or link on framework base main page calls this function below, sending the variable camefromhome (could be anything), with a value of camefromhome (again, could be anything), requesting that page_to_load be loaded into the div_to_fill div:

<script>
function doit(page_to_load)
{
new Ajax.Updater('div_to_fill', page_to_load,
{
method: 'get',
parameters: { camefromhome:'camefromhome' },
onCreate: load_started_function,
onComplete: load_finished_function
}
);
}
</script>

the page_to_load.php or similar contains this sniffer for sent token variable camefromhome to see if it was called by the framework or NOT! :

<?
if(($_SERVER['REQUEST_METHOD']=="GET")&&($_GET['camefromhome'] == 'camefromhome'))
{
//echo "loaded inside the framework, all clear";
}
else
{
...
}
?>


AJAX.Request Version:
Version that sends a variable with a Lightwindow javascript call and checks as above:

first modify lightwindow.js roughly line 1347 to look something like this:

<script>
_loadWindow : function() {
switch (this.windowType) {

case 'page' :
var pars = 'camefromhome=camefromhome';
var newAJAX = new Ajax.Request(
this.contentToFetch, {
method: 'get',
parameters: pars,
onComplete:
function(response){
$('lightwindow_contents').innerHTML += response.responseText;
this.resizeTo.height = $('lightwindow_contents').scrollHeight+(this.options.contentOffset.height);
this.resizeTo.width = $('lightwindow_contents').scrollWidth+(this.options.contentOffset.width);
this._processWindow();
}.bind(this)
}
);
break;

default : throw("Page Type could not be determined, please amend this lightwindow URL "+this.contentToFetch);
break;
}
}
</script>

then in the document getting loaded in check for the variable being passed or get outta there:

<?
if($_GET['camefromhome']=='camefromhome')
{}
else
{
header('Location:http://www.framework_home.com'); }
?>

Posted on 20 Nov 2009, 16:28 - Category: AJAX
Comments - Edit - Delete


Stop visitor from hitting AJAX loaded PHP content page directly $_SERVER['REQUEST_METHOD']

This was a real hunt.
Built a framework.
Load everything into it with AJAX.
Don't want visitors to be able to hit PHP content pages on their own.

$_SESSION variables work, but only on first hit.
If, for example, they came from a Google search result, it would force them into the framework,
but if they hit Back and then selected another result,
it wouldn't!

Global variables work for included php file content,
but are not accessible from php code loaded in via AJAX.

$_SESSION["PHP_SELF"] for the loaded content php page is the same with or without the framework,
it's simply that script's location on the server

Finally!
$_SESSION['REQUEST_METHOD'] seems to do the job.

if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
// echo "loaded inside the framework, all clear";
// this is because I SET the AJAX functions to POST!
}
else
{
// forward into the framework based
// based on $url = $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
// see forwarding post
// url method here is GET because page outside the framework is simple index.php?id=12 or similar!
// but logic works even if /another_page.php is
// loaded because the METHOD isn't POST

header("HTTP/1.1 301 Moved Permanently");
header("Location: $sendto");
}

Important Note:
This logic that checks METHOD is included in ALL pages dynamically loaded, but NOT initially loaded by the index.php/framework

keywords: POST, AJAX, PHP, php, Php, $_SERVER, SERVER, GET, framework, method, REQUEST_METHOD, request_method, server

Posted on 27 Oct 2009, 12:56 - Category: AJAX
Comments - Edit - Delete


AJAX photo upload

// index
// don't forget the xmlhttp.js (also posted in this blog)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="xmlhttp.js"></script>
<script type="text/javascript" src="functions.js"></script>
</head>
<body>
<div id="showimg"></div>
<form id="uploadform" action="process_upload.php" method="post" enctype="multipart/form-data" target="uploadframe">
Upload a File:<br />
<input type="file" id="myfile" name="myfile" />
<input type="submit" value="Submit" onclick="uploadimg(document.getElementById('uploadform')); return false;" />
<iframe id="uploadframe" name="uploadframe" src="process_upload.php" class="noshow"></iframe>
</form>
</body>
</html>

//process_upload.php

<?php
//process_upload.php

//Allowed file mime types.
$allowedtypes = array ("image/jpeg","image/pjpeg","image/png","image/gif");
//Where we want to save the file to.
$savefolder = "images";

/*
//First, kill off all older files.
if (is_dir ($savefolder)){
$scanarray = scandir ($savefolder);
$numdirs = count ($scanarray);
//parse the array
for ($i = 0; $i < $numdirs; $i++){
// make sure it is not the '.' or '..' files
if ($scanarray[$i] != "." && $scanarray[$i] !="..") {
//make sure it's a file
if (is_file ($savefolder . "/" . $scanarray[$i])){
unlink ($savefolder . "/" . $scanarray[$i]);
}
}
}
}
*/

//If we have a valid file.
if (isset ($_FILES['myfile'])){
//Then we need to confirm it is of a file type we want.
if (in_array ($_FILES['myfile']['type'],$allowedtypes)){
//Then we can perform the copy.
if ($_FILES['myfile']['error'] == 0){
$thefile = $savefolder . "/" . $_FILES['myfile']['name'];
if (!move_uploaded_file ($_FILES['myfile']['tmp_name'], $thefile)){
echo "There was an error uploading the file.";
} else {
//Signal the parent to load the image.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body>
<img src="<?=$thefile?>" onload="doneloading (parent,'<?=$thefile?>')" />
</body>
</html>
<?php
}
}
}
}
?>

// other functions to save into functions.js

//functions.js

//Function to determine when the process_upload.php file has finished executing.
function doneloading(theframe,thefile){
var theloc = "showimg.php?thefile=" + thefile
theframe.processajax ("showimg",theloc);
}

function uploadimg (theform){
//Submit the form.
theform.submit();
//Then display a loading message to the user.
setStatus ("Loading...","showimg");
}

//Function to set a loading status.
function setStatus (theStatus, theObj){
obj = document.getElementById(theObj);
if (obj){
obj.innerHTML = "<div class=\"bold\">" + theStatus + "</div>";
}
}

function changesize (img, sml){
//The display a loading message to the user.
theobj = document.getElementById("showimg");
if (theobj){
setStatus ("Loading...","showimg");
var loc = "thumb.php?img=" + img + "&sml=" + sml;
processajax ("showimg",loc);
}
}

Posted on 26 Oct 2009, 22:01 - Category: AJAX
Comments - Edit - Delete


AJAX xmlhttp.js get or post include

//Just save, upload, include
//xmlhttp.js

//Function to create an XMLHttp Object.
function getxmlhttp (){
//Create a boolean variable to check for a valid microsoft active X instance.
var xmlhttp = false;

//Check if we are using internet explorer.
try {
//If the javascript version is greater than 5.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
//If not, then use the older active x object.
try {
//If we are using internet explorer.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
//Else we must be using a non-internet explorer browser.
xmlhttp = false;
}
}

//If we are using a non-internet explorer browser, create a javascript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}

return xmlhttp;
}

//Function to process an XMLHttpRequest.
function processajax (serverPage, obj, getOrPost, str){
//Get an XMLHttpRequest object for use.
xmlhttp = getxmlhttp ();
if (getOrPost == "get"){
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
} else {
xmlhttp.open("POST", serverPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(str);
}
}

Posted on 26 Oct 2009, 21:55 - Category: AJAX
Comments - Edit - Delete


AJAX simple handwritten HTML AJAX example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Sample</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<!-- HERE IS SIMPLE AJAX HTTP OBJECT -->

<script type="text/javascript">
<!--

//Create a boolean variable to check for a valid Internet Explorer instance.
var xmlhttp = false;

//Check if we are using IE.
try {
//If the Javascript version is greater than 5.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
alert ("You are using Microsoft Internet Explorer.");
} catch (e) {
//If not, then use the older active x object.
try {
//If we are using Internet Explorer.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
alert ("You are using Microsoft Internet Explorder");
} catch (E) {
//Else we must be using a non-IE browser.
xmlhttp = false;
}
}

//If we are using a non-IE browser, create a javascript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
alert ("You are not using Microsoft Internet Explorer");
}

<!-- END OBJECT -->
<!-- HERE IS FUNCTION USING OBJECT -->

function makerequest(serverPage, objID) {

var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}

//-->
</script>


<body onload="makerequest ('content1.html','hw')">

<div align="center">

<h1>My Webpage</h1>

<a href="content1.html" onclick="makerequest('content1.html','hw'); return false;">Page 1</a> | <a href="content2.html" onclick="makerequest('content2.html','hw'); return false;">Page 2</a> | <a href="content3.html" onclick="makerequest('content3.html','hw'); return false;">Page 3</a> | <a href="content4.html" onclick="makerequest('content4.html','hw'); return false;">Page 4</a>

<div id="hw"></div>

</div>

</body>

</html>

keywords: AJAX, ajax, object, Object, XMLHTTP, ActiveXObject, innerHTML, document.getElementById

Posted on 26 Oct 2009, 21:21 - Category: AJAX
Comments - Edit - Delete


Pages: [1] [2]
Loading