Umar Waleed
Umar Waleed

Reputation: 31

How to store drop down selected value in variable on page load in php?

I have a drop downlist which has a selected value by default of Small. I want that when page loads that pre-selected value should be store in php variable.I have not submit button.

HTML Part

<form action="" method = "post">        
    <label style="font-weight:bold; font-size:18px; margin-top:8px; float:left; margin-right:40px;">Select Size: </label>
    <select class="styled" name="size" style="float:right; margin-right:80px;">
        <option value="Small" selected>Small</option>
        <option value="Medium">Medium</option>
        <option value="Large">Large</option>
    </select>                          
</form>

Php Part

<?php
$selected_val='';
if( isset ( $_POST['size'] ) ) {
    $selected_val = $_POST['size'];
}
echo $selected_val;
?>

But When I echo $selected_val this gives me nothing. can anybody please point out that what's the error and how to do this.. Thanks in advance.

Upvotes: 2

Views: 4333

Answers (1)

imran qasim
imran qasim

Reputation: 1050

here is your complete solution you need to use AJAX to achieve your task that whenver you load your document it will automatically get the selected value

   <!DOCTYPE html>
   <html lang="en">
  <head>
  <meta charset="UTF-8">
   <title>q</title>
 </head>
 <body onload="submitthis();">

<form action="" method = "post">

       <label style="font-weight:bold; font-size:18px; margin-top:8px; float:left; margin-right:40px;">Select Size: </label>
       <select onchange="submitthis();" id="sizes" class="styled" name="size" style="float:right; margin-right:80px;">
            <option value="Small" selected="">Small</option>
            <option value="Medium">Medium</option>
            <option value="Large">Large</option>
        </select>
        <div id="myDiv"></div>
 </form> 

<script>
function submitthis()
{
    var val = document.getElementById('sizes').value;
    console.log(val);
    var xmlhttp;
    if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
else
 {// code for IE6, IE5
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
    xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
 }
 }
 xmlhttp.open("GET","reply.php?size="+val,true);
 xmlhttp.send();
}

    </script>

and you need to make another file in same folder where is that html file exists with name reply.php and paste the following code

    <?php
        $selected_val='';
          if(isset($_GET['size'])){
            $selected_val = $_GET['size'];
        }
        echo $selected_val;
?>

i have made another small change that when you change the value from select box it will than load that crosponding value as well.

Upvotes: 1

Related Questions