NewDeveloper NewDeveloper - 1 year ago 108
HTML Question

Calling PHP function Onchange on Javascript

I want to call a function in php

onchange
in
select
of html,how can this be done?

html code

<div class="col-sm-4 form-group">
<label for="c_city">City</label>
<select class="form-control" id="c_city" onchange="<?php getArea(); ?>">
<option value="">Select City Name</option>
<!--populate value using php-->
<?php
$stmt ="SELECT * FROM Cities";
foreach ($con->query($stmt) as $row) {
?>
<option value="<?php echo $row['City_ID'];?>"><?php echo $row['City_Name'];?></option>
<?php
}
?>
</select>
</div>


PHP Functions Page

function getArea()
{
if(isset($_GET['c_city']))
{
$c_city = $_GET['c_city'];
echo $c_city;
}
}

Answer Source

You can try to use ajax to call the php script and receive results back to javascript.

For example in your html page:

<div class="col-sm-4 form-group">
   <label for="c_city">City</label>
   <select class="form-control" id="c_city" onchange="getArea()">
        <option value="">Select City Name</option>
        <!--populate value using php-->
        <?php
            $stmt ="SELECT * FROM Cities";
            foreach ($con->query($stmt) as $row) {
         ?>
         <option value="<?php echo $row['City_ID'];?>"><?php echo $row['City_Name'];?></option>
         <?php
          }
         ?>
   </select>
</div>

<script>
 function getArea(){
  var c_city = $('#c_city').val();
   $.ajax({
           type: 'POST',
           url: "get_area.php",
           data: {c_city:c_city},
           success: function(result){
               //do something here with return value like alert
               alert(result)
           }
     })
}
</script>

Then in your php script you can manipulate the value you receive from javascript

if(isset($_POST['c_city'])) 
    {
        $c_city = $_POST['c_city'];
        echo $c_city;
    }

Let me know if it helps or if you find a problem

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download