通过PHP json_encode将三个变量传递给javascript

here is my php code

 <?php
      session_start();
      require_once __DIR__ . '/../../core/FbChatMock.php';
      if (isset($_POST['id'])) 
       {
        $userId = (int) $_SESSION['user_id'];
        $id = htmlentities($_POST['id'],  ENT_NOQUOTES);
        $chat = new FbChatMock(); 
        $messages = $chat->getchat($userId, $id); 
        echo json_encode($messages);
       }
        $chat_converstaion = array();
        $chat_converstaion[] = '<table>';  
     ?> 

i want to pass $userId ,$id and $messages these three variable to json_encode function as i already pass $messages . here is my javascript function where i am using this json_encode

  getMessage:function(ID) {
  alert('function is at getMessage');
  var that = this;
  $.ajax({
  url: '../forms/ajax/get_messages.php',
  method:'post',
  data: {id: ID},
  success: function(data) {
    alert(data);
    var messages = JSON.parse(data);
    for (var i = 0; i < messages.length; i++)
      {
        var msg = messages[i];
        // alert (msg.message);
        fbChat.addUserMessage('',msg.message);
      }
        // alert(data);
        $('.msg_head').val('');
 //     that.getMessages();
    }
});
   },
  addUserMessage:function (user, message) 
     {
       msgBoxList = $('.msg_box').find('.msg_body');
       msgBoxList.append("<div class='msg_a'>"+message+"</div>");
     }
 };

How can i take that variable from php code to this javascript ajax call?

Just build an array with all the variables you wish to pass, then json_encode it :

<?php
  session_start();
  require_once __DIR__ . '/../../core/FbChatMock.php';
  if (isset($_POST['id'])) 
   {
    $userId = (int) $_SESSION['user_id'];
    $id = htmlentities($_POST['id'],  ENT_NOQUOTES);
    $chat = new FbChatMock(); 
    $messages = $chat->getchat($userId, $id); 
    $return = array('userId' => $userId, 'id' => $id, 'chat' => $chat, 'messages' => $messages);
    echo json_encode($return);
   }
    $chat_converstaion = array();
    $chat_converstaion[] = '<table>';  
 ?> 

Then build your JS variables from JSON.parse:

[...]
success: function(data) {
  alert(data);
  var json_data = JSON.parse(data);
  var userId = json_data.userId;
  var id = json_data.id;
  var chat = json_data.chat;
  var messages = json_data.messages;
[...]

With small modifications in PHP:

echo json_encode(['messages' => $messages, 'id' => $id, 'userId' => $userId]);

And JS:

    ...
    success: function(data) {
        var data = JSON.parse(data);
        var messages = data.messages;
        var id = data.id;
        var userId = data.userId;
        ...