HTML and AJAX problem

1

I have a chat that works with AJAX. Only, depending on some characters that the user types, 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 have this variable pass through the ajax without causing any errors. The .engl_chat is an input text, so I get its value through .val (), I know that if I get it with text () everything would be solved, but it will not. :

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');
    }
?>
    
asked by anonymous 01.07.2018 / 00:56

3 answers

1

Declare the following JS function,

function ajustadoEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

Then, in $.ajax , do

....
data: "msg=" + ajustadoEncodeURIComponent(msg),
----

Source: here

    
01.07.2018 / 01:17
1

By analyzing the code I saw that I get the message in the MSG variable that has a filter_var (), this filter removes the html tags, etc. So, if I send a msg just with a "<", it removes that tag, then $ msg becomes null, no value. soon it does not go into if with insert. So, as the IF does not have an else, php does not return anything, so ajax expects a JSON return, does not receive it, which causes the error: function ()

    
01.07.2018 / 01:52
0

Depending on your server configuration, any attempt to send < or / by the form may return error.

I use jQuery itself to handle the characters of sending to the server.

Test this and see if it's ok:

msg = $('<div/>').text(msg).html();

This makes, for example, that the text <script> seja transformado em &lt;script&gt;

If necessary, you can decode the server and return to the original text.

    
01.07.2018 / 01:24