44

How to get value of the get or post variable on page load using JavaScript?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohit Jain
  • 43,139
  • 57
  • 169
  • 274
  • related http://stackoverflow.com/questions/1409013/how-to-read-the-post-request-parameters-using-javascript – Adriano Jun 13 '13 at 08:34

9 Answers9

61

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.

Igor Zinov'yev
  • 3,676
  • 1
  • 33
  • 49
  • 12
    Rather 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
  • 4
    Not 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
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("+", " "));
    }
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

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>

MEH
  • 9
  • 3
0

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.

David Spector
  • 1,520
  • 15
  • 21
-1

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.

Marco
  • 319
  • 4
  • 13
  • 1
    This 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
-1

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>
Copes
  • 17
  • 2
  • 1
    This 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
-1
// 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
-1

/**
* 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
-1

Here is my answer for this given a string returnURL which is like http://host.com/?param1=abc&param2=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;
            }
        }
    }
    
imcdnzl
  • 1,011
  • 7
  • 13