John
John

Reputation: 952

Run script if selected value is changed

I want to run a PHP script if the value is changed in my dropdown. The PHP script should run an if else statement. Is it possible to run this script, without a form POST?

Here is my dropdown:

<select id="data" name="data" class="select2_single form-control">
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>

Here is the script I want to execute:

<?php
  if($_POST['data'] != '1') {
    echo  'Value 1 is selected';
  }
  if($_POST['data'] != '2') {
    echo 'Value 1 is selected';
  } else {
    echo  'No value selected';
  }
?>

Upvotes: 1

Views: 171

Answers (2)

Yosvel Quintero
Yosvel Quintero

Reputation: 19060

Also you can do this using just plain JavaScript:

var dataEl = document.querySelector('#data'),
    outputEl = document.querySelector('#output');

dataEl.onchange = function() {
  outputEl.innerText = dataEl.value 
    ? 'Value ' + dataEl.value + ' is selected'
    : 'No value selected';
};
<select id="data" name="data" class="select2_single form-control">
  <option value="">Select...</option>
  <option value="1">Data 1</option>
  <option value="2">Data 2</option>
</select>

<p id="output"></p>

Upvotes: 1

Pradeep Singh
Pradeep Singh

Reputation: 87

Try this js code for change value and handle post data at php end:

$(document).ready(function() {
  $("#data").change(function() {
    var id=$(this).val();       
    $.ajax
    ({
        type: "POST",
        data: 'id='+ id, 
        url : "dynamic_select.php",
        success: function(data) {
            //Handle returned data 
        }
    });

   });

});

Upvotes: 1

Related Questions