How to get value of the get or post variable on page load using JavaScript?
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.
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
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;
}
}
}
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.