skip to Main Content

Please Help me with this i want to display the value in php echo using ajax call,
the code is running without error.
the value get displayed on console console.log(id) when i select options from select field ,
and the value which i want to display using echo displays on console when i used console.log(data).

<script>
$('#select-user-id').click(function() {
  var id = $(this).val();

  $.ajax({
    url: 'ajax.php',
    type: 'POST',
    data: {
      id: id
    },
    success: function(data) {
      console.log(id);
      console.log(data);
    }
  });
})
</script>

But not displays on browser screen when i echo the value using.

$select_id = $_POST['id'];
echo "PHP: $select_id";

2

Answers


  1. What you need to do is assign the value in a span or other html tags on success.

    success: function(data) {
         yourSpan.value = data;
    }
    
    Login or Signup to reply.
  2. Just like what Ainz had mentioned, what you would want to do is send the value to a tag and display it there.

    <!-- Be sure that your jQuery file is added -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  
    
    <select name="select-user-id" id="select-user-id">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
    
    //Add a div as a holder for the returned values from your AJAX file
    <div class="displayData"></div>
    
    <script>
    $('#select-user-id').on('change', function() {
      var id = $(this).val();
      /* Also make sure that you have the correct path for your file  */
      $.ajax({
        url: 'ajax.php',
        type: 'POST',
        data: {
          "id": id
        },
    
        success: function(data) {
          $('.displayData').html(data);
        }
      });
    });
    </script>
    

    You can also append your variable to the string like below.

    <?php
       $select_id = $_POST['id'];
       echo 'PHP: '.$select_id;
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search