Sending data with ajax

3

I have an online chat that works with ajax and PHP . However, strangely, when I type only an interrogation ( ? ) and send the jQuery , it returns an error in the console. ajax enters error() and the query ( ? ) is inserted in the database, but with strange characters type:

jQuery33106296323571939269_1534100132138.

JavaScript:

$('#envia_chat_id').keyup(function(e){
                    if(e.which === 13 & $('#envia_chat_id').attr('class') === 'envia_chat'){
                        if(trim($('.envia_chat').val()) != ''){
                            var msgenvio = $('.envia_chat').val();
                            var msgrender = msgenvio.replace(/</g, '&lt;').replace(/>/g, '&gt;');
                            $('#chat_box').append('<div class="msg user_' + $('.time_user').val() + '"><span>'+ $('.nick_user').val() + ': </span>'+ msgrender +'</div)');
                            $('.envia_chat').val('');
                            $('.envia_chat').removeAttr('class');
                            $('#chat_box').scrollTop($('#chat_box').prop("scrollHeight"));
                            $('#envia_chat_id').attr('placeholder','Aguarde para enviar outra...');
                            console.log('msg='+ msgenvio + '&type=enviaMsg&lobby=' + $('.lobbyid').val() + '&time=' + $('.time_user').val() + '&nick=' + $('.nick_user').val());
                        $.ajax({
                            url:'chat.php',
                            dataType: 'JSON',
                            type: 'POST',
                            data: 'msg='+ msgenvio + '&type=enviaMsg&lobby=' + $('.lobbyid').val() + '&time=' + $('.time_user').val() + '&nick=' + $('.nick_user').val(),
                            success: function(data){
                                console.log(data);
                                setTimeout(function(){
                                    $('#envia_chat_id').attr('class','envia_chat');
                                    $('#envia_chat_id').attr('placeholder','Chat...');
                                }, 4000);

                            },
                            error: function(data){
                                console.log(data);
                                $('#chat_box').append('<div class="msg msg_erro">Tente novamente enviar esta mensagem.</div)');
                                $('#chat_box').scrollTop($('#chat_box').prop("scrollHeight"));
                                $('#envia_chat_id').attr('class','envia_chat');
                                $('#envia_chat_id').attr('placeholder','Chat...');
                            }
                            });
                        }

                    }
});

PHP:

<?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'];
            $acao = $_POST['type'];
            $id_lobby = (is_numeric($_POST['lobby'])==true) ? $_POST['lobby'] : NULL;
            $tempo_atual = date("Y-m-d H:i:s");
                    $msg = (isset($_POST['msg'])==true and $_POST['msg'] != '') ? filter_var($_POST['msg'], FILTER_SANITIZE_SPECIAL_CHARS) : NULL;
                    $time = (isset($_POST['time']) == true and $_POST['time'] == 'azul' or $_POST['time'] == 'laranja' or $_POST['time'] == 'ambos') ? $_POST['time'] : NULL;
                    $nick = (isset($_POST['nick']) == true) ? $_POST['nick'] : NULL;
                    if(trim($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('erro_null');
                    }
    }else{
        echo Erro('erro_faltam');
    }
?>
    
asked by anonymous 12.08.2018 / 21:32

2 answers

3

By sending the ? character to one of the data variables (concatenating the variables as a URL string, as you are doing) jQuery will treat the URL as JSONP and will register a callback when Ajax returns request. Since no callback was given (even though it was not intended as a result of dataType being "JSON"), it will result in the mentioned error, such as:

  

parsererror Error: jQuery33100166499243115803_1534312585291 was not   called

jQuery created and tried to call a jQuery33100166499243115803_1534312585291 callback that does not exist.

Send the data in data in object form, not in string form URL:

data: {
   msg: msgenvio,
   type: 'enviaMsg',
   lobby: $('.lobbyid').val(),
   time: $('.time_user').val(),
   nick: $('.nick_user').val()
},
    
15.08.2018 / 08:02
1

Form data POST when sent to the server, usually has application/x-www-form-urlencoded formatting by default. And, as the name itself suggests, the data is encoded as URL data.

Characters like ? and & are special characters in a url, and they, if sent as literal content, need to be encoded.

To do this, there are two ways:

  • Use data , as explained in previous answer.
  • Use the $.param function to set the parameters of your url.

See how $.param behaves:

$(function () {

    console.log($.param({question: 'Qual é o seu nome?'}));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Note that the result of calling $.param caused the last string to change completely. This is because the encoding is used for url.

Out of curiosity, jQuery by default uses $.param in the object you pass as parameter to data in the $.ajax call.

    
17.08.2018 / 14:04