[php] Get variable from PHP to JavaScript

I want to use a PHP variable in JavaScript. How is it possible?

This question is related to php javascript

The answer is


You can pass PHP Variables to your JavaScript by generating it with PHP:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>

You can print the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.


You can pass PHP Variables to your JavaScript by generating it with PHP:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>

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:

$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

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:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

Most web pages nowadays use a combination of the two.


You can print the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.


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:

$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

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:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

Most web pages nowadays use a combination of the two.


<?php 
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>

This is the easiest way of passing a php variable to javascript without Ajax.

You can also use something like this:

var i = "<?php echo json_encode($j); ?>";

This said to be safer or more secure. i think


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 generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>

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:

$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

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:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

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:

  1. Via PHP's $_GET array (associative array).
  2. 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;
}

JSFiddle demo

_x000D_
_x000D_
function main(){_x000D_
    var imaginaryUrl = "http://example.com/webapp/?search=how%20to%20use%20Google&the_answer=42",_x000D_
        qs = new QuerystringTable(imaginaryUrl);_x000D_
_x000D_
    urlbox.innerHTML = "url: " + imaginaryUrl;_x000D_
    _x000D_
    logButton(_x000D_
        "qs.getKeys()",_x000D_
        qs.getKeys()_x000D_
        .map(arrowify)_x000D_
        .join("\n")_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        'qs.getValue("search")',_x000D_
        qs.getValue("search")_x000D_
        .arrowify()_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        'qs.getValue("the_answer")',_x000D_
        qs.getValue("the_answer")_x000D_
        .arrowify()_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        "qs.getQuerystring()",_x000D_
        qs.getQuerystring()_x000D_
        .arrowify()_x000D_
    );_x000D_
}_x000D_
_x000D_
function arrowify(str){_x000D_
    return "  -> " + str;_x000D_
}_x000D_
_x000D_
String.prototype.arrowify = function(){_x000D_
    return arrowify(this);_x000D_
}_x000D_
_x000D_
function log(msg){_x000D_
    txt.value += msg + '\n';_x000D_
    txt.scrollTop = txt.scrollHeight;_x000D_
}_x000D_
_x000D_
function logButton(name, output){_x000D_
    var el = document.createElement("button");_x000D_
    _x000D_
    el.innerHTML = name;_x000D_
    _x000D_
    el.onclick = function(){_x000D_
        log(name);_x000D_
        log(output);_x000D_
        log("- - - -");_x000D_
    }_x000D_
    _x000D_
    buttonContainer.appendChild(el);_x000D_
}_x000D_
_x000D_
function QuerystringTable(_url){_x000D_
    // private_x000D_
    var url = _url,_x000D_
        table = {};_x000D_
_x000D_
    function buildTable(){_x000D_
        getQuerystring().split('&').filter(validatePair).map(parsePair);_x000D_
    }_x000D_
_x000D_
    function parsePair(pair){_x000D_
        var splitPair = pair.split('='),_x000D_
            key       = decodeURIComponent(splitPair[0]),_x000D_
            value     = decodeURIComponent(splitPair[1]);_x000D_
_x000D_
        table[key] = value;_x000D_
    }_x000D_
_x000D_
    function validatePair(pair){_x000D_
        var splitPair = pair.split('=');_x000D_
_x000D_
        return !!splitPair[0] && !!splitPair[1];_x000D_
    }_x000D_
_x000D_
    function validateUrl(){_x000D_
        if(typeof url !== "string"){_x000D_
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;_x000D_
        }_x000D_
_x000D_
        if(url == ""){_x000D_
            throw "QuerystringTable() :: Empty string given for argument <string url>";_x000D_
        }_x000D_
    }_x000D_
_x000D_
    // public_x000D_
    function getKeys(){_x000D_
        return Object.keys(table);_x000D_
    }_x000D_
_x000D_
    function getQuerystring(){_x000D_
        var string;_x000D_
_x000D_
        validateUrl();_x000D_
        string = url.split('?')[1];_x000D_
_x000D_
        if(!string){_x000D_
            string = url;_x000D_
        }_x000D_
_x000D_
        return string;_x000D_
    }_x000D_
_x000D_
    function getValue(key){_x000D_
        var match = table[key] || null;_x000D_
_x000D_
        if(!match){_x000D_
            return "undefined";_x000D_
        }_x000D_
_x000D_
        return match;_x000D_
    }_x000D_
_x000D_
    buildTable();_x000D_
    this.getKeys        = getKeys;_x000D_
    this.getQuerystring = getQuerystring;_x000D_
    this.getValue       = getValue;_x000D_
}_x000D_
_x000D_
main();
_x000D_
#urlbox{_x000D_
    width: 100%;_x000D_
    padding: 5px;_x000D_
    margin: 10px auto;_x000D_
    font: 12px monospace;_x000D_
    background: #fff;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
#txt{_x000D_
    width: 100%;_x000D_
    height: 200px;_x000D_
    padding: 5px;_x000D_
    margin: 10px auto;_x000D_
    resize: none;_x000D_
    border: none;_x000D_
    background: #fff;_x000D_
    color: #000;_x000D_
    displaY:block;_x000D_
}_x000D_
_x000D_
button{_x000D_
    padding: 5px;_x000D_
    margin: 10px;_x000D_
    width: 200px;_x000D_
    background: #eee;_x000D_
    color: #000;_x000D_
    border:1px solid #ccc;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
button:hover{_x000D_
    background: #fff;_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<p id="urlbox"></p>_x000D_
<textarea id="txt" disabled="true"></textarea>_x000D_
<div id="buttonContainer"></div>
_x000D_
_x000D_
_x000D_

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&ampersand=this%20thing%3A%20%26, for example, will internally become:

{
    "foo?"      : "bar baz",
    "ampersand" : "this thing: &"
}

All the work is done for you at instantiation.

Here's how to use it:

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

$_GET=function(key,def){
    try{
        return RegExp('[?&;]'+key+'=([^?&#;]*)').exec(location.href)[1]
    }catch(e){
        return def||''
    }
}

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 generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>

You can print the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.


You can pass PHP Variables to your JavaScript by generating it with PHP:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>

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:

$.getJSON('http://foo/bar.php', {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

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:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

Most web pages nowadays use a combination of the two.


You can print the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.


<?php 
$j=1;
?>
<script>
var i = "<?php echo $j; ?>";
//Do something
</script>
<?php
echo $j;
?>

This is the easiest way of passing a php variable to javascript without Ajax.

You can also use something like this:

var i = "<?php echo json_encode($j); ?>";

This said to be safer or more secure. i think


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:

  1. Via PHP's $_GET array (associative array).
  2. 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;
}

JSFiddle demo

_x000D_
_x000D_
function main(){_x000D_
    var imaginaryUrl = "http://example.com/webapp/?search=how%20to%20use%20Google&the_answer=42",_x000D_
        qs = new QuerystringTable(imaginaryUrl);_x000D_
_x000D_
    urlbox.innerHTML = "url: " + imaginaryUrl;_x000D_
    _x000D_
    logButton(_x000D_
        "qs.getKeys()",_x000D_
        qs.getKeys()_x000D_
        .map(arrowify)_x000D_
        .join("\n")_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        'qs.getValue("search")',_x000D_
        qs.getValue("search")_x000D_
        .arrowify()_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        'qs.getValue("the_answer")',_x000D_
        qs.getValue("the_answer")_x000D_
        .arrowify()_x000D_
    );_x000D_
    _x000D_
    logButton(_x000D_
        "qs.getQuerystring()",_x000D_
        qs.getQuerystring()_x000D_
        .arrowify()_x000D_
    );_x000D_
}_x000D_
_x000D_
function arrowify(str){_x000D_
    return "  -> " + str;_x000D_
}_x000D_
_x000D_
String.prototype.arrowify = function(){_x000D_
    return arrowify(this);_x000D_
}_x000D_
_x000D_
function log(msg){_x000D_
    txt.value += msg + '\n';_x000D_
    txt.scrollTop = txt.scrollHeight;_x000D_
}_x000D_
_x000D_
function logButton(name, output){_x000D_
    var el = document.createElement("button");_x000D_
    _x000D_
    el.innerHTML = name;_x000D_
    _x000D_
    el.onclick = function(){_x000D_
        log(name);_x000D_
        log(output);_x000D_
        log("- - - -");_x000D_
    }_x000D_
    _x000D_
    buttonContainer.appendChild(el);_x000D_
}_x000D_
_x000D_
function QuerystringTable(_url){_x000D_
    // private_x000D_
    var url = _url,_x000D_
        table = {};_x000D_
_x000D_
    function buildTable(){_x000D_
        getQuerystring().split('&').filter(validatePair).map(parsePair);_x000D_
    }_x000D_
_x000D_
    function parsePair(pair){_x000D_
        var splitPair = pair.split('='),_x000D_
            key       = decodeURIComponent(splitPair[0]),_x000D_
            value     = decodeURIComponent(splitPair[1]);_x000D_
_x000D_
        table[key] = value;_x000D_
    }_x000D_
_x000D_
    function validatePair(pair){_x000D_
        var splitPair = pair.split('=');_x000D_
_x000D_
        return !!splitPair[0] && !!splitPair[1];_x000D_
    }_x000D_
_x000D_
    function validateUrl(){_x000D_
        if(typeof url !== "string"){_x000D_
            throw "QuerystringTable() :: <string url>: expected string, got " + typeof url;_x000D_
        }_x000D_
_x000D_
        if(url == ""){_x000D_
            throw "QuerystringTable() :: Empty string given for argument <string url>";_x000D_
        }_x000D_
    }_x000D_
_x000D_
    // public_x000D_
    function getKeys(){_x000D_
        return Object.keys(table);_x000D_
    }_x000D_
_x000D_
    function getQuerystring(){_x000D_
        var string;_x000D_
_x000D_
        validateUrl();_x000D_
        string = url.split('?')[1];_x000D_
_x000D_
        if(!string){_x000D_
            string = url;_x000D_
        }_x000D_
_x000D_
        return string;_x000D_
    }_x000D_
_x000D_
    function getValue(key){_x000D_
        var match = table[key] || null;_x000D_
_x000D_
        if(!match){_x000D_
            return "undefined";_x000D_
        }_x000D_
_x000D_
        return match;_x000D_
    }_x000D_
_x000D_
    buildTable();_x000D_
    this.getKeys        = getKeys;_x000D_
    this.getQuerystring = getQuerystring;_x000D_
    this.getValue       = getValue;_x000D_
}_x000D_
_x000D_
main();
_x000D_
#urlbox{_x000D_
    width: 100%;_x000D_
    padding: 5px;_x000D_
    margin: 10px auto;_x000D_
    font: 12px monospace;_x000D_
    background: #fff;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
#txt{_x000D_
    width: 100%;_x000D_
    height: 200px;_x000D_
    padding: 5px;_x000D_
    margin: 10px auto;_x000D_
    resize: none;_x000D_
    border: none;_x000D_
    background: #fff;_x000D_
    color: #000;_x000D_
    displaY:block;_x000D_
}_x000D_
_x000D_
button{_x000D_
    padding: 5px;_x000D_
    margin: 10px;_x000D_
    width: 200px;_x000D_
    background: #eee;_x000D_
    color: #000;_x000D_
    border:1px solid #ccc;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
button:hover{_x000D_
    background: #fff;_x000D_
    cursor: pointer;_x000D_
}
_x000D_
<p id="urlbox"></p>_x000D_
<textarea id="txt" disabled="true"></textarea>_x000D_
<div id="buttonContainer"></div>
_x000D_
_x000D_
_x000D_

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&ampersand=this%20thing%3A%20%26, for example, will internally become:

{
    "foo?"      : "bar baz",
    "ampersand" : "this thing: &"
}

All the work is done for you at instantiation.

Here's how to use it:

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

$_GET=function(key,def){
    try{
        return RegExp('[?&;]'+key+'=([^?&#;]*)').exec(location.href)[1]
    }catch(e){
        return def||''
    }
}

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 generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>