I am creating a chat in php and nodejs using library socket.io
the thing is that from my index.php
I make a call ajax that inserts the data
in the database and I return the answer through a array
to ajax, then
I send that data with socket.io
with emit()
, but at the time of reading that data returns [object Object]
.
THIS IS MY CODE
const http = require('http');
const path = require('path');
const express = require('express');
const connect = require('connect');
const app = express();
const server = app.listen(3000);
const io = require('socket.io').listen(server);
io.on('connection',socket=>{
console.log('NEW CLIENT');
//esta es la accion que se recive desde el cliente
socket.on('client-message',function (data) {
console.log(data);
//aqui el servidor emite el mensaje a todos los clientes
io.sockets.emit('server-message', data);
})
})
//voy a establecer un puerto si no tomas el 3000
app.set('port' , process.env.PORT || 3000)
//voy a recivir el puerto
server.listen(app.get('port') ,()=>{
console.log('conectado con el servidor '+app.get('port'))
})
call ajax
<?php
session_starts();
$msg=$_POST['msg'];
$id=$_POST['id'];
$yo=$_SESSION['id'];
$insert=mysqli_query(INSERT INTO message(msg,de,para,fecha)VALUES('$msg','$yo','$id',now()) ");
$query=mysqli_query($conexion,"SELECT * FROM registro WHERE id='$yo' ");
$row=mysqli_fetch_array($query);
$my_pic=$row['avatar'];
echo json_encode(array('pic'=>$my_pic,'msng'=>$msg);
?
customer
$(function () {
var sockets = io.connect( 'http://localhost:8080/' );
//obteniendo los elementos del Dom
var formulario = $("#message-form");
var mensajebox = $("#chat");
var myMessage = $("#message");
var myId = $("#id");
formulario.submit( e =>{
e.preventDefault();
//console.log(mensaje.val());
//emitimos mensaje al servidor
$.ajax({
url:"insert_message.php",
type:"POST",
data:formulario.serialize(),
datatype:"json",
success:function(data){
//recivimos el array desde php y lo enviamos al servidor
socket.emit('client-message',data);
//limpiar input despues de enviar
myMessage.val("");
}
})
});
/*aqui nos toca escuchar el mensaje atraves de la palabra clave del servidor*/
socket.on('server-message',function(data){
//aqui elegimos donde mostrar el mensaje del servidor
mensajebox.append(data.pic + data.msg+'<br>');
});
})
In the server console my array is reflected very well, like this: <"pic","andy.png","msg","hola soy andy">
.
As you can see what I want is to show my photo and my message.
Any ideas or tips on how to do it, no novice with arrays and json?