MatrixHyperLoop
MatrixHyperLoop

Reputation: 33

Changing a PHP variable value with a select option list in ajax

I have a php variable called $photographerNum that i want the value of to change depending upon value in my drop down field on my page, what would the javascript look like for this as well as how to receive the new value to update the php variable?

    <!DOCTYPE html>
<html>
<body>
<? $photographerNum = 1; ?>
<p>Select an item from the list.</p>
<select id="photographerNum" onchange="myFunction()">
  <option value="Item1">Item1
  <option value="Item2">Item2
  <option value="Item3">Item3
  <option value="Item4">Item4
</select>
<script type="text/javascript">
function myFunction() {
    var itemSelected = document.getElementById("photographerNum").value;
    document.getElementById("demo").innerHTML = "You selected: " + itemSelected ;
}
</script>
<p id="demo"> - photoNum=<? echo $photographerNum ?></p>
</body>
</html>

Upvotes: 1

Views: 3021

Answers (1)

rescobar
rescobar

Reputation: 1305

Try this, when you select a new item a form is triggered which outputs the value of the selected item, after that, you can send the variable and process it in server-side.

<?php 
$photographerNum = 1;
 echo 'Initial value photographerNum::' . $photographerNum;
?>  
 <form name="myform" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
   <select name="photographerNum" id="IdphotographerNum"   onchange="myform.submit();">
    <option value="0">Selecte an item
    <option value="1">Item1
    <option value="2">Item2
    <option value="3">Item3
    <option value="4">Item4
</select>
</form>

<?php
if (isset($_POST['photographerNum'])) {
   echo 'New value photographerNum::' . $_POST['photographerNum'];
}
?>  

Upvotes: 2

Related Questions