1

I can't seem to get the selected option value from the select.php into the value_selected.php file.The console.log(data) displayed nothing. Why is that?

select.php

<!DOCTYPE html>  
<html>  
<head></head>
<body>
<script src="js/jquery-3.2.0.min.js"></script>

<form method="POST" action="">
<label for "sel_opt">Select value: </label>
<select name="sel_opt" id="sel_opt">
    <option value="1">1</option>
    <option value="2">2</option>
</select>
<input name="submit" type="submit" id="submit" value="Submit">
</form>

<div id="result"></div>

<script>
$(document).ready(function(){  
           $("#submit").click(function(){ 
             $.ajax({  
                          url:"http://localhost/value_selected.php",  
                          type:"POST",  
                          success:function(data)  
                          {  
                            console.log(data);
                            $('#result').html(data);  
                          }  
                     });  
                });  
           }); 
</script>
</body>
</html>

value_selected.php

<?php
$output = "";
if(isset($_POST["submit"])) {
 if(isset($_POST["sel_opt"])) {
$val = $_POST["sel_opt"];
 if ($val == 1) {  
      $output = "<p>Value 1 selected</p>";
 }   else {
    $output = "<p>Value 2 selected</p>";
 }
 echo $output;
}
 ?>
cathy305
  • 57
  • 1
  • 1
  • 8
  • 2
    You didnt send data with the AJAX request. So you never enter the `if(isset($_POST["submit"])) {` and never output anything. Add an `else` to that and you'll see you never enter. – chris85 Apr 07 '17 at 15:45
  • @chris85 Ah, I see. So how do I do that? – cathy305 Apr 07 '17 at 15:48
  • You need to pass a `data: { name: "John", location: "Boston" }` field to the request. See http://api.jquery.com/jquery.ajax/ in the example the fields in the PHP would be `$_POST['name']` and `$_POST['location']` the values would be `john` and `boston`. – chris85 Apr 07 '17 at 15:50
  • Check this http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php – Ravinder Reddy Apr 07 '17 at 15:52
  • @chris85 That link is really helpful. I removed the `if(isset($_POST["submit"]))` and passed `data: {sel_opt: $("#sel_opt").val()}` and it runs smoothly. Thank you – cathy305 Apr 07 '17 at 16:15

1 Answers1

1

Add data: to your ajax config object with form values.

<script>
$(document).ready(function(){
    $("#submit").click(function(){
        $.ajax({
            url:"http://localhost/value_selected.php",
            type:"POST",
            data: $('form').serialize(),
            success:function(data)
            {
                console.log(data);
                $('#result').html(data);
            }
        });
    });
});
</script>
pbogut
  • 857
  • 1
  • 9
  • 22
  • I edited my previous comment. I tried this and remove the `if(isset($_POST["submit"]))` from the value_selected.php and it works! – cathy305 Apr 07 '17 at 16:04