Question

I am trying to loop over a JSON output from PHP and assign a list item to each index.

Im having two separate issues.

  • The encode is adding weird slashes and quotes when they are not needed.
  • I get a type error (not valid argument) when parsing the JSON string even when set from a test php array.

PHP

$data= json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
echo json_encode($data);

JSON

"[
    {\"id\":\"1\",\"user_id\":\"1\",\"message\":\"MSG 1\"},
    {\"id\":\"2\",\"user_id\":\"1\",\"message\":\"MSG 2\"},
    {\"id\":\"3\",\"user_id\":\"1\",\"message\":\"MSG 3 \"},
]"

jQuery

  $.ajax({ url: 'chat.php',
    dataType: 'json',
    type: 'post',
    error: function(statusCode, errorThrown) {
                updateError(statusCode, errorThrown);
            },
    success: function(data){

         $.each(data, function() {
                $.each(this, function(k, v) {
                    $('<li data-msgid="'+data.id+'">' + data.user_id + '::' + data.message + '</li>').appendTo('#chat_area');
                 });
            });

        }

});

Im using ajax call rather than json as I will eventually be passing data in this same function. Any help is much appreciated.

Était-ce utile?

La solution

You are encoding twice:

$data= json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
echo json_encode($data);

Remove the first one and only encode the final data:

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
...
echo json_encode($data);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top