title: Passing variables from javascript via ajax to php
body: <p>I am new to jquery and ajax. I have a script here where i need to pass variables to a php file. That php will be then encoded to  div#chat-body. I am trying to pass the receiver variable to the load-messages.php via POST but I am getting the following error: <strong>"Undefined index: receiver in xxxx/scripts/load_messages.php on line 8"</strong>. I think there is something wrong with my syntax or im doing this totally wrong.</p>
  
  <p>script.js</p>
  
  <pre><code>$('input#send-message').on('click', function(){
  alert("test");
  var message = $('input#input-message').val();
  var sender= $('input#sender').val();
  var receiver= $('input#receiver').val();
  
      if($.trim(message)!=''){
          $.post('scripts/messaging.php', {message: message, sender: sender, receiver:receiver}, function(data){
          //output after sending message  
  
          });     
          //load message to  chat-body div
  
          $.ajax({
          url: 'scripts/load_messages.php',
          type: "POST",
          data: {receiver: receiver},
          success: function(data){
              $('#chat-body').html(data);
              //$('#chat-body').scrollTop($('#chat-body')[0].scrollHeight); 
          }
      });
      }});
  </code></pre>
  
  <p>load-messages.php</p>
  
  <pre><code> &lt;?php 
      session_start();
      require('config.php');
      require('chat_functions.php');
  
  
  $messages = get_msg($_SESSION['user_id'], $_POST['receiver']);
  
  foreach($messages as $message){
      if($message['sender'] == $_SESSION['user_id'])  {
          ?&gt;&lt;div id = "you_message"&gt;
  
          &lt;?php echo '&lt;strong&gt; You: &lt;/strong&gt;&lt;br /&gt;';
          echo $message['message'].'&lt;br /&gt;&lt;br /&gt;';?&gt;
          &lt;/div&gt;&lt;!--you_message--&gt;
          &lt;?php   
      }
  
      else{
          ?&gt;&lt;div id="recipient_message"&gt;
          &lt;?php echo '&lt;strong&gt;'.get_name($_POST['receiver']).'&lt;/strong&gt;&lt;br /&gt;';
          echo $message['message'].'&lt;br /&gt;&lt;br /&gt;';?&gt;
          &lt;/div&gt; &lt;!--recipient_message --&gt;
          &lt;?php
          }
      }
  
      ?&gt;
  </code></pre>