HTML and AJAX problem

Asked

Viewed 81 times

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)?

  • The characters that give the error are: < and . at least the ones I tested gave error.

  • Yeah. Basically.

  • But I get a JSON back, it returns me {status: "Success"}

  • You know which version of your PHP?

  • You’re not doing INSERT twice with the same primary key?

  • php version 7.2.5

  • 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.

Show 3 more comments

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 the $.ajax, do

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

Source: here

  • The characters that are giving error, that I tested are < and .

  • The full post I get is this: msg=%5C&type=enviaMsg&lobby=10&time=azul&nick=MODERADOR, and even then it gives error I’m not understanding.

  • What a mistake it is?

  • it enters error: ajax Function()()

  • I know; but what message comes in data?

  • comes the status: Success that I programmed in the backend to return.

  • So what’s the problem? If you coded the back-end to return "Success" when actually giving error, it was not of you paste the code of the back-end here tb?

  • If it enters the error: Function() of ajax, doesn’t mean it couldn’t connect to the chat.php file? I thought that was it

  • No, it means that the back-end gave HTTP Error code different than 200.

  • oloco. did not know. vlw, I will post the backend there above

  • Ready. I posted up

  • You’re not doing INSERT twice with the same primary key?

  • and how would I do that?

  • Ué, making INSERT of duplicate values.

  • 1

    I think I understand my problem

  • 1

    Analyzing the code I saw that I receive the Message in the MSG variable that has a filter_var(), this filter removes the html tags, etc. So, if I send an msg with only a "<", it removes this tag, then the $msg becomes null with no value. so it does not enter the Insert.

  • 1

    Logoo, since IF does not have an Else, php does not return anything, so ajax expecting a JSON return, does not receive it, which causes error: Function()

Show 12 more comments

1

Analyzing the code I saw that I receive the Message in the MSG variable that has a filter_var(), this filter removes the html tags, etc. So, if I send an msg with only a "<", it removes this tag, then the $msg becomes null with no value. then it does not enter the if with Insert. Therefore, since IF does not have an Else, php does not return anything, so ajax expecting a JSON return, does not receive it, which causes error: Function()

0

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

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

Test like this and see if it’s okay:

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

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

If necessary, you can do Code on the server and return to the original text.

  • which, I didn’t understand ahusahdsaud

  • use thus: date: 'msg='+ $('<div/>'). text(msg). html(),

  • Okay, but like, I can explain where this <div came from/>?

  • 1

    It is a temporary div, never enters the DOM. It is only to take the content of the input and do the

Browser other questions tagged

You are not signed in. Login or sign up in order to post.