Hi guys can How to assign $_GET value to a variable using pure JavaScript I have HTML structure not php
Asked
Active
Viewed 70 times
0
-
1Why not to use javascript to read get: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – Dmytro Pastovenskyi Oct 17 '15 at 14:56
2 Answers
1
You could do something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length;
key += '=';
while (i-- > 0) {
if (params[i].lastIndexOf(key, 0) === 0)
return params[i].slice(key.length);
}
return false;
}
You may also want to consider if you want to use decodeURIComponent
on these values as they may be URI encoded
If you want to also permit keys to be URI encoded then this method starts to have issues and you would have to create an Object mapping, which would look something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length,
j,
o = Object.create(null);
for (i = 0; i < params.length; ++i) {
j = params[i].indexOf('=');
if (j === -1) // how do you want to treat found but no value?
o[decodeURIComponent(params[i])] = null;
else
o[decodeURIComponent(params[i].slice(0, j))] = decodeURIComponent(params[i].slice(j + 1));
}
if (key in o) return o[key];
return false; // how do you wan to treat not found?
}
You could also create and cache this Object in advance instead of generating it for each invocation

Paul S.
- 64,864
- 9
- 122
- 138
-1
combine the php code and javascript code !
var x=<?php echo $_GET['whatever'];?>;
so first the php code is being executed server-side and then it's result in html is assigned to a variable in javascript ...

NO-ONE_LEAVES_HERE
- 127
- 1
- 11
-
-
1First of all, the question specifically asks for JavaScript only solution. Secondly this will result in a syntax error if the get parameter is anything other than a number. – JJJ Oct 17 '15 at 14:58
-
in the title of question ... he wrote $_GET ... which is the notation of php !!! so i think he wanted ! – NO-ONE_LEAVES_HERE Oct 17 '15 at 14:58
-
So you're saying that when he wrote "using pure JavaScript" he meant "using PHP", and in the question when he wrote "not PHP" he meant "yes PHP"? – JJJ Oct 17 '15 at 15:01
-
:D i mean using php and javascript ! see the other answer it is 10 lines of code and mine is just 1 – NO-ONE_LEAVES_HERE Oct 17 '15 at 15:03