Passing Javascript variables to Php
Here is a tutorial which will explain how to pass Javascript variables to Php.This tutorial works only for files under the same server
Aim:To pass document.referrer variable to Php and to write the referrer variable on a text file;
First let us create two file called 1a.html and 2a.html
1a.html will contain a link to 2a.html
and 2a.html will contain just two javascript calls one will call a file called xml1.js
Here is the source of 1a.html
<a href=’http://www.ramanean.com/java/2a.html’>2</a>
Source of 2a.html
<html>
<head>
</head>
<body>
<script src=”xml1.js”></script>
<script type=”text/javascript”>
change1();
</script>
Here First we are calling xml.js javascript and then calling change1() function in it
Source of xml1.js
var xmlHttp
function change1()
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert (”Your browser does not support AJAX!”);
return;
}
var shan=document.referrer;
var url=”78.php”;
url=url+”?q=”+shan;
xmlHttp.open(”GET”,url,true);
xmlHttp.send(null);
}function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(”Msxml2.XMLHTTP”);
}
catch (e)
{
xmlHttp=new ActiveXObject(”Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}
In the above function function GetXmlHttpObject() is nothing but creating Xmlhttpobject by which get function will be routed (AJAX).Do n’t worry about that if you need to more about there go to http://www.w3schools.com/ajax/ajax_source.asp.
Now let us go to the second line ,Here we are declaring change1 function and then we checking whether browser supports xml if not browser will display an error message indicating that “your Browser does n’t support AJAX”
Now let me explain what these four lines contain
var s =document.referrer; // javascript variable you are going to pass
var url=”78.php”; //Url aof the Php script you are going to pass javascript varaibles
url=url+”?q=”+shan;// adding javascript variables to the url
xmlHttp.open(”GET”,url,true); //callingthe php script
xmlHttp.send(null);//calling the php script
The php file is like this
<?php
$q=$_GET[”q”];//Getting the javascript variable
$file=file_put_contents(’ip1.txt’,$q);//writing the variable to file
?>
by this you can pass variables to a php script and from php you can insert any data into your database;
