send javascript value to PHP session
Moderator: General Moderators
send javascript value to PHP session
hi, i need some idea on how to pass a value (from a javascript variable) to PHP Session?. thanks.
You can do it by creating some hidden fields while submitting your form, here's an example.
Code: Select all
<?php
// This code displays your post data.
echo '<pre>' . htmlspecialchars(print_r($_POST, 1)) . '</pre>';
?>
<script type="text/javascript">
// This function allows you to pass JS values to form.
function add2form(frm, val) {
// Create some variables first.
var i;
// Delete old JS values.
for (i = frm.childNodes.length - 1; i >= 0; i --) {
if (frm.childNodes[i].nodeName.toLowerCase() == 'input'
&& frm.childNodes[i].type.toLowerCase() == 'hidden'
&& frm.childNodes[i].name.substr(0, 4) == 'js__') {
frm.removeChild(frm.childNodes[i]);
}
}
// Create new JS values.
var nip;
for (i in val) {
nip = document.createElement('input');
nip.type = 'hidden';
nip.name = 'js__' + i;
nip.value = val[i];
frm.appendChild (nip);
}
}
// Create an object.
var jsValues = {};
// Define its value.
jsValues.screenWidth = screen.width;
jsValues.screenHeight = screen.height
</script>
<!-- This is an example form, I added an onsubmit event handler to add some variables to form. -->
<form action="" onsubmit="add2form(this, jsValues);" method="post">
<input type="submit" value="Click here to submit your screen resolution" />
</form>if you need more understanding about his code:joboy wrote:the DtTvb:
i need ample time to study your codes..for some objects are new to me.
by the way, your effort is highly appreciated, thanks for the answer.
The javascript passes the value into a hidden field. (in his example he creates a hidden field via javascript).
You can also add a hidden field manually too.
so basically, when a form is submitted, the value is passed into the hidden field before the POST request begin.
Good solution.. no need for ajax