1
I have a chat that works with AJAX. However, depending on some characters that the user type, AJAX does not work, I do not know why, but it does not work. Therefore, I need to remove the HTML from the msg variable, and make sure that such variable can pass through ajax without causing any errors. The . envia_chat is an input text, so I took its value through the . val(), I know that if I got it with text() it would all be solved, but it does not give. :(
The code, summarized, looks something like this:
$.ajax({
url:'chat.php',
dataType:'JSON',
type: 'POST',
data: 'msg='+ msg,
success: function(data){
//FUNCAO DE SUCESSO
alert('Msg enviada');
},
error: function(data){
alert('Ocorreu um erro');
}
});
<?php
session_start();
function Erro($texto){
$array = array('status' => $texto);
return json_encode($array, JSON_PRETTY_PRINT);
}
function Sucesso($texto){
$array = array('status' => $texto);
return json_encode($array, JSON_PRETTY_PRINT);
}
if(isset($_SESSION['login_id']) and !empty($_SESSION['login_id']) and isset($_POST['type']) and isset($_POST['lobby']) and is_numeric($_POST['lobby']) == true){
require('connection.php');
$id = $_SESSION['login_id'];
$verifica_user = mysqli_query($conexao, "SELECT id FROM users_buscando WHERE id_user = '$id' and playing = '1' and id_lobby != '0'");
if(mysqli_num_rows($verifica_user) == 1){
$acao = $_POST['type'];
$id_lobby = (is_numeric($_POST['lobby'])==true) ? $_POST['lobby'] : NULL;
$tempo_atual = date("Y-m-d H:i:s");
$busca_user = mysqli_query($conexao, "SELECT * FROM users WHERE id = '$id'");
$dados = mysqli_fetch_array($busca_user);
$msg = (isset($_POST['msg'])==true and $_POST['msg'] != '') ? filter_var($_POST['msg'], FILTER_SANITIZE_STRING) : NULL;
$time = (isset($_POST['time']) == true and $_POST['time'] == 'azul' or $_POST['time'] == 'laranja') ? $_POST['time'] : NULL;
$nick = (isset($_POST['nick']) == true) ? $_POST['nick'] : NULL;
if($msg != NULL and $time != NULL and $nick != NULL){
$insere_msg = mysqli_query($conexao, "INSERT INTO chat (id_user, content, id_lobby, timestamp, time, nick) VALUES ('$id', '$msg', '$id_lobby', '$tempo_atual', '$time', '$nick')");
if($insere_msg === true){
echo Sucesso('success');
}
}
}else{
echo Erro('notplaying');
}
}else{
echo Erro('erro');
}
?>
have tried
data: "msg=" + encodeURIComponent(msg)
?– Marcelo Shiniti Uchimura
The characters that give the error are: < and . at least the ones I tested gave error.
– Vitor Leite
Yeah. Basically.
– Vitor Leite
But I get a JSON back, it returns me {status: "Success"}
– Vitor Leite
You know which version of your PHP?
– Sam
You’re not doing
INSERT
twice with the same primary key?– Marcelo Shiniti Uchimura
php version 7.2.5
– Vitor Leite
Blz... the error is somewhere in this PHP code... puts
console.log(data.responseText);
inside the error function: and see in the console the PHP error that returns.– Sam