通过AJAX将li数据值传递回同一页面

I'm trying to pass the data-value of the < li > I clicked to PHP in the same page. I'm using AJAX to pass the data to PHP, to be used in querying. I think the ajax request is working, but the php code inside the if is not running.

The codes:

offices.php

<?php
    include 'connect.php';
    $page = 'offices';
    include 'header.php';

    if (isset($_POST['postdata'])){
        $filter1 = $_POST['postdata'];
        echo $filter1;
    }
?>

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

        <div class="filter1">
            <ul>
                <li class="fteacher" data-value="teacher">Professor</li>
                <li class="foffice" data-value="office">Gabinete</li>
            </ul>
        </div>

        <script src="js/offices.js"></script>
    </body>
 </html>

offices.js

$('.filter1 li').click(function(){
 $.ajax({ 
     type: 'POST',
     url: 'offices.php',
     data: {'postdata': $(this).attr('data-value')},
     success: function(msg){
           alert('Success'); 
      }
 });
});

I tried the code you provided, but had to ommit the two includes at the beginning of your PHP script, and it worked. Testing was done using file_put_contents("test.txt", "test"); in the if-clause.

You may have a look at what the PHP script returns by using alert(msg). Note that everything after the PHP part is returned, too. It might also help to use error_reporting(E_ALL) in the PHP to search for problems in the included scripts.

Please try this. Hope you are only expecting the output $filter1

<?php
   if (isset($_POST['postdata'])){
      $filter1 = $_POST['postdata'];
      echo $filter1;
   }else {
      include 'connect.php';
      $page = 'offices';
      include 'header.php';
?>
    <!DOCTYPE html>
     <html>
        <head>
           <script src="js/jquery.min.js"></script>
        </head>
        <body>
            <div class="filter1">
                <ul>
                    <li class="fteacher" data-value="teacher">Professor</li>
                    <li class="foffice" data-value="office">Gabinete</li>
                </ul>
            </div>
            <script src="js/offices.js"></script>
        </body>
     </html>
    <?php
        }
    ?>