tags:

views:

147

answers:

4

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

+4  A: 

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
Rather than writing the POST value directly, you could use `json_encode`
Ken Keenan
@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
+1  A: 

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
A: 
Anil Namde
You can get GET parameters from the URL (location.search)
Thilo
A: 

I just woke up and am very groggy so I may not be clear but you can find anything in the form using the DOM. If x contains the form object, then x.method tells you whether it's POST or GET. x.action is also available.

Or am I misunderstanding? Christmas parties kill me every time.

Rob