0

I have the same problem here, but what I need is to get the value of selected option then save it in a php variable rather than a textbox. I spent almost 2days searching for my gold. Any help will do.thank you.

Edited Here is how I write the code.

<script>
$(document).ready(function () {
  $("#country").change(
   function () {
       var options = {
                url: "test.php",
               type: "post",
               dataType: "json",
               data: "country=" + $(this).val(), //build your data string here
             success: function (json) {
                 $("#textbox").val(json.country);
             }
           };
       $.ajax(options);
   }
 );
 });
</script>
<select id="country" name="country">
 <option value="Delhi" >India</option>
 <option value="manila" >phil</option>
  <option value="tokyo" >japan</option>
</select>
<?php

  @$d = $_POST['country'];
  echo $d;
  var_dump($d);


?>
Community
  • 1
  • 1
user2446342
  • 19
  • 1
  • 1
  • 4

2 Answers2

4

You can do like this. (jQuery Ajax example)

on dropdown selection:

<select id="city">
   <option value="New York">New York</option>
   <option value="London">London</option>
   <option value="Washington DC">Washington DC</option>
</select>

JS Code

$(document).ready(function() {
   $('city').onchange(function() {
      $.ajax({
        type: "GET",
        url: "some.php",
       data: { city: this.val() }
      }).done(function( msg ) {
        alert( "Data Saved: " + msg );
      });
   });
});

PHP

some.php

you can get the value by using GET or REQUEST methods.

$city = $_GET['city'];
$city = $_REQUEST['city'];
skparwal
  • 1,086
  • 6
  • 15
1

I will take the same example and modify and give you an answer.

<script>
$(document).ready(function () {
   $("#country").change(
       function () {
           var options = {
                    url: "/path/to/your.php",
                   type: "post",
                   dataType: "json",
                   data: "country=" + $(this).val(), //build your data string here
                 success: function (json) {
                     $("#textbox").val(json.country);
                 }
               };
           $.ajax(options);
       }
   );
});
</script>
<select id="country" name="country">
  <option value="Delhi" >India</option>
  <option value="manila" >phil</option>
  <option value="tokyo" >japan</option>
</select>

in order to capture the value on the server side in your php file

 $var = $_POST['country'];
 $json = array('country' => $var);
 header("Content-Type: application/json");
 echo json_encode($json);

Updated code will return the country back to the script via json and write to a <input type=text field which has id=textbox

DevZer0
  • 13,433
  • 7
  • 27
  • 51