title: Rewrite a JSON array in PHP so that jQuery can read it?
body: <p>I'm trying to create a JSON array in PHP that jQuery can use and access but for some reason It doesn't work. I get no error messages on  the client side nor in the server logs and if I access enc.php directly, it does work, but I'm not sure if the output is correct (the array format).
  <br>
  <br>
  <strong>What I want:</strong>
  I would like to access the data with jQuery using data[i][0] for the ID ([i] because it's in a loop), and data[i][1] for the message and so on.</p>
  
  <p><em>Maybe I'm trying to do this the wrong way, if so please help me by pointing me in the right direction or provide an example.</em></p>
  
  <p>My code:</p>
  
  <p>The current <strong>PHP code</strong>:</p>
  
  <pre><code>$result = $stmt-&gt;get_result();
  while ($row = $result-&gt;fetch_assoc()) {
    $fetchedid = $row['id'];
    $fetchedkey = $row['chat_key'];
    $fetchednonce = $row['chat_nonce'];
    $fetcheduser = $row['chat_user'];
    $fetchedmsg = $row['chat_msg'];
  
    $plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
    $out = array('id' =&gt; $fetchedid, 'msg' =&gt; $plainmsg, 'user' =&gt; $fetcheduser);
    header('Content-Type: application/json');
    ob_end_clean();
    echo json_encode($out);
  }
  </code></pre>
  
  <p><strong>Result:</strong></p>
  
  <pre><code>{"id":297,"msg":"test message","user":"john"}
  </code></pre>
  
  <p><strong>My jQuery (Ajax) code:</strong></p>
  
  <pre><code>$.ajax({
     type: "GET",
     url: "enc.php",
     dataType: "json",
     success: function(data) {
       console.log('Update success called');
       if (data == 2) {
         // No messages to fetch
       } else if (data == 3) {
         // Cookie Tampering detected
       } else if (data == 5) {
         $("#chat").remove();
         alert("Den här chatten är stängd (tiden har gått ut).");
         window.location.href = "/?logout=safe";
       }
       else {
       for (i = 0; i &lt; data.length; ++i) {
         var mid = data[i][0];
         $.cookie("cmid", mid);
         var from = data[i][1];
         var msg = data[i][2];
         $("#chat").append('&lt;div class="left spotmsg"&gt;&lt;div class="chat-avatar pull-left"&gt;&lt;img src="/img/them.png" alt="avatar" width="48" height="48"&gt;&lt;/div&gt;&lt;div class="message"&gt;&lt;div class="arrow-left"&gt;&lt;/div&gt;&lt;p&gt;&lt;strong&gt;@'+from+'&lt;/strong&gt;&lt;/p&gt;&lt;p class="txt"&gt;'+msg+'&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;');
       }
       $('textarea').focus();
       $(".chat_area").animate({ scrollTop: $(".chat_area")[0].scrollHeight}, 1000);
   }
  }
  });
  </code></pre>