javascript - Undefined index:usernames

I??�m trying to pass php variable to another class using ajax to another class known as post.php. It keep saying in another class post.php that ???undefined index:usernames??? when I try to print it in another class as $echo $nameOfUser can anyone reckon what am I doing wrong? Thanks index.php

<?php
 session_start();
   ?>
  <html>
  <head>
    <script src=??? https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js ???</script>
  </head>

   <body>
    <?php
   global $username;
     $nameOfUser = $_SESSION['name'];
        ?>
        
        <script>
        var username = '<?php echo $nameOfUser ?>';
        console.log(username); //it prints the right username here

        $.ajax({
            type:'POST',
            url: 'post.php',
            data: {function : 'testing',  usernames: username},
            success: function() {
           alert('success');
            }


        });
        </script>

post.php

 <?php
 session_start();
 ini_set('display_errors', '1');
  ini_set('error_reporting', E_ALL);
   ?>
  <html>
  <head>
  </head>
  <body>
  <hr>
  <?php
   $username = $_POST['usernames'];

   echo $username; // it says here undefined index usernames


   if ($functionname == 0){
    testing($username);
    }

  function testing($username) {
    echo 'my name is: '; //it prints that
   echo $username;   

  }

  ?>
 </body>
 </html>

Answer

Solution:

$_POST[...] reads data from the request.

When you make a POST request to the URL, the data in that request will be available to the PHP handling that URL.

When you make another, separate request, to the URL (or another URL that uses some of the same code) then it will have access to that second request.

It won't have access to the data from the first request.

If you want to persist that data between requests then you need to store it somewhere (such as a session or a database) and retrieve it when you want to use it.

Answer

Solution:

Your ajax request type is 'POST' and you should use $_POST instead of $_GET. Or you can use $_REQUEST variable that containt $_GET, $_POST and $_COOKIE.

Source