This is what's usually called AJAX, and it is useful to give web pages a more
dynamic and desktop-like feel (you don't have to refresh the entire page to communicate
with PHP).
Other techniques are simpler. As others have suggested, you can simply generate the
variable data from your PHP script:
Update: I completely rewrote this answer. The old code is still there, at the bottom, but I don't recommend it.
There are two main ways you can get access GET variables:
Via PHP's $_GET array (associative array).
Via JavaScript's location object.
With PHP, you can just make a "template", which goes something like this:
<script type="text/javascript">
var $_GET = JSON.parse("<?php echo json_encode($_GET); ?>");
</script>
However, I think the mixture of languages here is sloppy, and should be avoided where possible. I can't really think of any good reasons to mix data between PHP and JavaScript anyway.
It really boils down to this:
If the data can be obtained via JavaScript, use JavaScript.
If the data can't be obtained via JavaScript, use AJAX.
If you otherwise need to communicate with the server, use AJAX.
Since we're talking about $_GET here (or at least I assumed we were when I wrote the original answer), you should get it via JavaScript.
In the original answer, I had two methods for getting the query string, but it was too messy and error-prone. Those are now at the bottom of this answer.
Anyways, I designed a nice little "class" for getting the query string (actually an object constructor, see the relevant section from MDN's OOP article):
function QuerystringTable(_url){
// private
var url = _url,
table = {};
function buildTable(){
getQuerystring().split('&').filter(validatePair).map(parsePair);
}
function parsePair(pair){
var splitPair = pair.split('='),
key = decodeURIComponent(splitPair[0]),
value = decodeURIComponent(splitPair[1]);
table[key] = value;
}
function validatePair(pair){
var splitPair = pair.split('=');
return !!splitPair[0] && !!splitPair[1];
}
function validateUrl(){
if(typeof url !== "string"){
throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;
}
if(url == ""){
throw "QuerystringTable() :: Empty string given for argument <string url>";
}
}
// public
function getKeys(){
return Object.keys(table);
}
function getQuerystring(){
var string;
validateUrl();
string = url.split('?')[1];
if(!string){
string = url;
}
return string;
}
function getValue(key){
var match = table[key] || null;
if(!match){
return "undefined";
}
return match;
}
buildTable();
this.getKeys = getKeys;
this.getQuerystring = getQuerystring;
this.getValue = getValue;
}
It's much more robust, doesn't rely on regex, combines the best parts of both the previous approaches, and will validate your input. You can give it query strings other than the one from the url, and it will fail loudly if you give bad input. Moreover, like a good object/module, it doesn't know or care about anything outside of the class definition, so it can be used with anything.
The constructor automatically populates its internal table and decodes each string such that ...?foo%3F=bar%20baz&ersand=this%20thing%3A%20%26, for example, will internally become:
var qst = new QuerystringTable(location.href);
qst.getKeys() // returns an array of keys
qst.getValue("foo") // returns the value of foo, or "undefined" if none.
qst.getQuerystring() // returns the querystring
That's much better. And leaving the url part up to the programmer both allows this to be used in non-browser environments (tested in both node.js and a browser), and allows for a scenario where you might want to compare two different query strings.
var qs1 = new QuerystringTable(/* url #1 */),
qs2 = new QuerystringTable(/* url #2 */);
if (qs1.getValue("vid") !== qs2.getValue("vid")){
// Do something
}
As I said above, there were two messy methods that are referenced by this answer. I'm keeping them here so readers don't have to hunt through revision history to find them. Here they are:
1) Direct parse by function. This just grabs the url and parses it directly with RegEx
Easy peasy, if the query string is ?ducksays=quack&bearsays=growl, then $_GET('ducksays') should return quack and $_GET('bearsays') should return growl
Now you probably instantly notice that the syntax is different as a result of being a function. Instead of $_GET[key], it is $_GET(key). Well, I thought of that :)
Here comes the second method:
2) Object Build by Loop
onload=function(){
$_GET={}//the lack of 'var' makes this global
str=location.search.split('&')//not '?', this will be dealt with later
for(i in str){
REG=RegExp('([^?&#;]*)=([^?&#;]*)').exec(str[i])
$_GET[REG[1]]=REG[2]
}
}
Behold! $_GET is now an object containing an index of every object in the url, so now this is possible:
$_GET['ducksays']//returns 'quack'
AND this is possible
for(i in $_GET){
document.write(i+': '+$_GET[i]+'<hr>')
}
This is definitely not possible with the function.
Again, I don't recommend this old code. It's badly written.
It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:
You can pass PHP Variables to your JavaScript by generating it with PHP:
I think the easiest route is to include the jQuery javascript library in your webpages, then use JSON as format to pass data between the two.
In your HTML pages, you can request data from the PHP scripts like this:
In bar.php you can do this:
This is what's usually called AJAX, and it is useful to give web pages a more dynamic and desktop-like feel (you don't have to refresh the entire page to communicate with PHP).
Other techniques are simpler. As others have suggested, you can simply generate the variable data from your PHP script:
Most web pages nowadays use a combination of the two.
Update: I completely rewrote this answer. The old code is still there, at the bottom, but I don't recommend it.
There are two main ways you can get access
GET
variables:$_GET
array (associative array).location
object.With PHP, you can just make a "template", which goes something like this:
However, I think the mixture of languages here is sloppy, and should be avoided where possible. I can't really think of any good reasons to mix data between PHP and JavaScript anyway.
It really boils down to this:
Since we're talking about
$_GET
here (or at least I assumed we were when I wrote the original answer), you should get it via JavaScript.In the original answer, I had two methods for getting the query string, but it was too messy and error-prone. Those are now at the bottom of this answer.
Anyways, I designed a nice little "class" for getting the query string (actually an object constructor, see the relevant section from MDN's OOP article):
JSFiddle demo
It's much more robust, doesn't rely on regex, combines the best parts of both the previous approaches, and will validate your input. You can give it query strings other than the one from the url, and it will fail loudly if you give bad input. Moreover, like a good object/module, it doesn't know or care about anything outside of the class definition, so it can be used with anything.
The constructor automatically populates its internal table and decodes each string such that
...?foo%3F=bar%20baz&ersand=this%20thing%3A%20%26
, for example, will internally become:All the work is done for you at instantiation.
Here's how to use it:
That's much better. And leaving the url part up to the programmer both allows this to be used in non-browser environments (tested in both
node.js
anda browser
), and allows for a scenario where you might want to compare two different query strings.As I said above, there were two messy methods that are referenced by this answer. I'm keeping them here so readers don't have to hunt through revision history to find them. Here they are:
Again, I don't recommend this old code. It's badly written.
It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:
json_encode
functionjson_decode
functionYou can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:
This is the easiest way of passing a php variable to javascript without Ajax.
You can also use something like this:
This said to be safer or more secure. i think
You can print the PHP variable into your javascript while your page is created.
Of course this is for simple variables and not objects.