How to get value of the get or post variable on page load using JavaScript?
-
related http://stackoverflow.com/questions/1409013/how-to-read-the-post-request-parameters-using-javascript – Adriano Jun 13 '13 at 08:34
9 Answers
You can't get the value of POST variables using Javascript, although you can insert it in the document when you process the request on the server.
<script type="text/javascript">
window.some_variable = '<?=$_POST['some_value']?>'; // That's for a string
</script>
GET variables are available through the window.location.href
, and some frameworks even have methods ready to parse them.

- 3,676
- 1
- 33
- 49
-
12Rather than writing the POST value directly, you could use `json_encode` – Ken Keenan Dec 25 '09 at 12:15
-
@Ken Keenan: you're right thanks! And also you can do some validation before that. I was just trying to show my point. – Igor Zinov'yev Dec 25 '09 at 12:23
-
4Not doing any kind of encoding or validation means that the code as written is [vulnerable to XSS](https://www.owasp.org/index.php/XSS). – Quentin Aug 08 '16 at 14:22
You can only get the URI arguments with JavaScript.
// get query arguments
var $_GET = {},
args = location.search.substr(1).split(/&/);
for (var i=0; i<args.length; ++i) {
var tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
}
}

- 643,351
- 109
- 780
- 844
This is my first Answer in stackoverflow and my english is not good. so I can't talk good about this problem:)
I think you might need the following code to get the value of your or tags.
this is what you might need:
HTML
<input id="input_id" type="checkbox/text/radio" value="mehrad" />
<div id="writeSomething"></div>
JavaScript
function checkvalue(input , Write) {
var inputValue = document.getElementById(input).value;
if(inputValue !="" && inputValue !=null) {
document.getElementById(Write).innerHTML = inputValue;
} else {
document.getElementById(Write).innerHTML = "Value is empty";
}
}
also, you can use other codes or other if in this function like this:
function checkvalue(input , Write) {
var inputValue = document.getElementById(input).value;
if(inputValue !="" && inputValue !=null) {
document.getElementById(Write).innerHTML = inputValue;
document.getElementById(Write).style.color = "#000";
} else {
document.getElementById(Write).innerHTML = "Value is empty";
}
}
and you can use this function in your page by events like this:
<div onclick="checkvalue('input_id','writeSomthing')"></div>
I hope my code will be useful for you
Write by <Mehrad Karampour>

- 9
- 3
The simplest technique:
If your form action attribute is omitted, you can send a form to the same HTML file without actually using a GET HTTP access, just by using onClick on the button used for submitting the form. Then the form fields are in the elements array document.FormName.elements . Each element in that array has a value attribute containing the string the user provided (For INPUT elements). It also has id and name attributes, containing the id and/or name provided in the form child elements.

- 1,520
- 15
- 21
When i had the issue i saved the value into a hidden input:
in html body:
<body>
<?php
if (isset($_POST['Id'])){
$fid= $_POST['Id'];
}
?>
... then put the hidden input on the page and write the value $fid with php echo
<input type=hidden id ="fid" name=fid value="<?php echo $fid ?>">
then in $(document).ready( function () {
var postId=document.getElementById("fid").value;
so i got my hidden url parameter in php an js.

- 319
- 4
- 13
-
1This is insecure. It allows anyone to insert arbitrary HTML in your application (they can post `"` and break out of the attribute) – Mark Fowler Sep 21 '17 at 16:29
With little php is very easy.
HTML part:
<input type="text" name="some_name">
JavaScript
<script type="text/javascript">
some_variable = "<?php echo $_POST['some_name']?>";
</script>

- 17
- 2
-
1This is totally insecure. If someone posts something containing `"` then they can follow it with arbitrary JavaScript. – Mark Fowler Sep 21 '17 at 16:26
-
Also note that escaping `"` is not enough, you need to guard against `` too. Use of `json_encode` (which now escapes backslash) is recommended – Mark Fowler Sep 21 '17 at 16:27
-
A secure technique is to write a function in PHP that scans the arguments in $_POST and makes each one a global variable (or a class static variable) with "Arg" appended to its name. This prevents an argument from having the same name as one of your own global variables. So, argument "a" would become variable "$aArg" in your program code. I'll post the code here if anyone needs it, upon request, as an answer. NEVER include user input directly in any HTML or JavaScript as you did here. That is a sure way to get hacked, but good. – David Spector Nov 27 '18 at 17:31
// Captura datos usando metodo GET en la url colocar index.html?hola=chao
const $_GET = {};
const args = location.search.substr(1).split(/&/);
for (let i=0; i<args.length; ++i) {
const tmp = args[i].split(/=/);
if (tmp[0] != "") {
$_GET[decodeURIComponent(tmp[0])] = decodeURIComponent(tmp.slice(1).join("").replace("+", " "));
console.log(`>>${$_GET['hola']}`);
}//::END if
}//::END for
/**
* getGET: [Funcion que captura las variables pasados por GET]
* @Implementacion [pagina.html?id=10&pos=3]
* @param {[const ]} loc [capturamos la url]
* @return {[array]} get [Devuelve un array de clave=>valor]
*/
const getGET = () => {
const loc = document.location.href;
// si existe el interrogante
if(loc.indexOf('?')>0){
// cogemos la parte de la url que hay despues del interrogante
const getString = loc.split('?')[1];
// obtenemos un array con cada clave=valor
const GET = getString.split('&');
const get = {};
// recorremos todo el array de valores
for(let i = 0, l = GET.length; i < l; i++){
const tmp = GET[i].split('=');
get[tmp[0]] = unescape(decodeURI(tmp[1]));
}//::END for
return get;
}//::END if
}//::END getGET
/**
* [DOMContentLoaded]
* @param {[const]} valores [Cogemos los valores pasados por get]
* @return {[document.write]}
*/
document.addEventListener('DOMContentLoaded', () => {
const valores=getGET();
if(valores){
// hacemos un bucle para pasar por cada indice del array de valores
for(const index in valores){
document.write(`<br>clave: ${index} - valor: ${valores[index]}`);
}//::END for
}else{
// no se ha recibido ningun parametro por GET
document.write("<br>No se ha recibido ningún parámetro");
}//::END if
});//::END DOMContentLoaded
Here is my answer for this given a string returnURL which is like http://host.com/?param1=abc¶m2=cde. It's fairly basic as I'm beginning at JavaScript (this is actually part of my first program ever in JS), and making it simpler to understand rather than tricky.
Notes
- No sanity checking of values
- Just outputting to the console - you'll want to store them in an array or something
this is only for GET, and not POST
var paramindex = returnURL.indexOf('?'); if (paramindex > 0) { var paramstring = returnURL.split('?')[1]; while (paramindex > 0) { paramindex = paramstring.indexOf('='); if (paramindex > 0) { var parkey = paramstring.substr(0,paramindex); console.log(parkey) paramstring = paramstring.substr(paramindex+1) // +1 to strip out the = } paramindex = paramstring.indexOf('&'); if (paramindex > 0) { var parvalue = paramstring.substr(0,paramindex); console.log(parvalue) paramstring = paramstring.substr(paramindex+1) // +1 to strip out the & } else { // we're at the end of the URL var parvalue = paramstring console.log(parvalue) break; } } }

- 1,011
- 7
- 13