PDA

View Full Version : Updating the value of a php session variable using javascript/ajax



Yatuz
14 Apr 2011, 07:30 PM
Hey everyone, I'm relatively new to web development and wanted some help regarding php session variables and JavaScript. From what I've heard this problem cannot be solved without Ajax. I've tried searching for a solution to this problem on the internet but haven't found a solution that fixed my particular issue. So here goes.

I want to update the value of a session variable using a JavaScript function. The JavaScript function is called by a drop-down menu using the onchange event once the option "apple" is selected.

<?php

session_start();
$_SESSION['toggle']=1;

?>

<html>
<head>
<script type=text/javascript>

function GetSelectedItem() {
if(document.getElementById("dropdown1").value=="apple"){
<?php $_SESSION['toggle]=0;?>
}
}

</script>
</head>
<body>
<!-- html for the dropdown goes here. the drop down works on its own-->

<?php print $_SESSION['toggle'];?>

</body>
</html>

I get the value 0 printed on the page. I already know this shouldn't work, because php is server side language and is compiled on the server. Whereas JavaScript is client side and runs on the browser. I've read that an Ajax call back can be used to send a post request to a php file which can then in-turn set the session variable to a particular value. Can someone give me an example which fits my problem.

I hope I made some sense.

Thankyou for your help in advance.