-1

I've the next code on PHP:
[chat/verChatsUSUARIO]

$chats = [];
try {
    $query = $this->db->connect()->query('SELECT * FROM chats_publicos_usuarios WHERE USUARIO_IP = :IP AND ID > :ID');
    $query->execute([   
        'IP' => ! empty($datos['IP']) ? $datos['IP'] : NULL,
        'ID' => ! empty($datos['ID']) ? $datos['ID'] : NULL,
    ]);

    while ($row = $query->fetch()) {
    $chats['chats'] = $row;
    }

    echo json_encode($chats);
}


Then, the next JQUERY code:
[chats.js]

idChat = 1
function verMisChats(direccionIP) {
    $.ajax({
        url: 'chat/verChatsUSUARIO',
        type: 'POST',
        data: {
            ip: direccionIP,
            id: idChat,
        },
        success: function(r) {
            console.log(r)
            if (r.chats) {
                r.chats.forEach(chat => {
                    idChat = chat.ID
                    $("#sinChats").hide();
                    $("#misChats").append(verMiChat(chat));
                })
            }
            verMisChats(direccionIP)
        }
    })
}

And I get this result when use that jquery function:
Jquery result


But when try foreach for every query result (in this example just 1 result), I get this error: Error jquery foreach

  • `chats` isn't an array, why would it have a `forEach` method? – Quentin May 31 '22 at 07:16
  • Why is not array? Result appear as {chat:...} on console.log – Alex Maluquer May 31 '22 at 07:17
  • If it was an array it would use `[]` not `{}` – Quentin May 31 '22 at 07:18
  • in this case, how should be code to make array? – Alex Maluquer May 31 '22 at 07:19
  • *how should be code to make array* - by making it an array in the php before you json encode it. It *looks like* you've attempted that in the php, but `$chats['chats'] = ` will overwrite the *single* value with `$row` each iteration and your result would be (pseudo) `r.chats=$row.last` - so your array of `$chats` -> `r` and `$chats.chat` -> `r.chats` it doesn't help that you've used the same variable name `$chats / .chats` so getting confused with what you're returning. – freedomn-m May 31 '22 at 07:34
  • {"chats":[{"ID":"8","0":"8","USUARIO":"Alex MF","1":"Alex MF","USUARIO_IP":"213.98.48.218","2":"0.0.0.0","DEPARTAMENTO":"Otros","3":"Otros","ASUNTO":"Prova 1","4":"Prova 1","ACTIVE":"0","5":"0","BANNED":"0","6":"0"}]} I've this, now what? – Alex Maluquer May 31 '22 at 08:08
  • How many results does (should) your query `SELECT * FROM chats_publicos_usuarios WHERE USUARIO_IP = :IP AND ID > :ID` actually return? (not your code, that query) – freedomn-m May 31 '22 at 08:23
  • Take out the actual data and you have `{"chats":[{...}]}` - which is an array with one entry. – freedomn-m May 31 '22 at 08:24

0 Answers0