Page 1 of 1

send javascript value to PHP session

Posted: Fri Feb 16, 2007 4:31 am
by joboy
hi, i need some idea on how to pass a value (from a javascript variable) to PHP Session?. thanks.

Posted: Fri Feb 16, 2007 4:55 am
by jmut
javascript is client side.
php is server side. So direct answer is you cannot.

You can achieve this through:
1. Form submit
2. javascript clicking link.. And link contains GET data you need.
3. Ajax call.

Posted: Fri Feb 16, 2007 9:27 am
by the DtTvB
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>

Posted: Fri Feb 23, 2007 3:10 am
by joboy
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.

Posted: Fri Feb 23, 2007 11:40 pm
by Tommy1402
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.
if you need more understanding about his code:
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 :-)

Posted: Tue Feb 27, 2007 1:27 am
by joboy
Tommy1402:

the concept is now more clear to me. thanks.