views:

262

answers:

4

I suppose I could use PHP to access $_GET variables from JavaScript:

<script>
var to = $_GET['to'];
var from = $_GET['from'];
</script>
<script src="realScript" type="text/javascript"></script>

But perhaps it's even simpler. Is there a way to do it directly from JS?

+4  A: 

Look at

window.location.search

It will contain a string like this: ?foo=1&bar=2

To get from that into an object, some splitting is all you need to do:

var parts = window.location.search.substr(1).split("&");
var $_GET = {};
for (var i = 0; i < parts.length; i++) {
    var temp = parts[i].split("=");
    $_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}

alert($_GET['foo']); // 1
alert($_GET.bar);    // 2
nickf
`decodeURIComponent`, not `unescape`, which will get `+`s and all non-ASCII characters wrong.
bobince
cheers, bobince - edited now.
nickf
A: 

As others have explained you can parse page URL from JS to get the variables.

You could also use AJAX in the page which submits the values. It really depends on what kind of information you're passing and then returning back to the user. (It's definitely not simpler or more direct way of doing it, just an alternative approach)

Maiku Mori
A: 

I suppose you were thinking this:

<script type="text/javascript">

    var to = "<?= $_GET['to']; ?>";
    var from = "<?= $_GET['from']; ?>";

</script>

...this would just be syntax-correction of your idea :)

ile
you would want to be sure you escape out double quotes in the strings too ;) otherwise that's a security risk.
nlaq
You mean `var to = \" ... \"`?
ile
+2  A: 

Here's another idea:

<script type="text/javascript">

var $_GET = <?php echo json_encode($_GET); ?>;

alert($_GET['some_key']);
// or
alert($_GET.some_key);

</script>
Ionuț G. Stan