Sending data with ajax

Asked

Viewed 304 times

3

I have a online chat that works with ajax and PHP. Yet, oddly enough, when I enter only one question (?) and sending the jQuery, returns an error in the console. The ajax gets into the error() and the interrogation (?) is inserted into the seat, but with strange characters like:

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');
    }
?>
  • 1

    Tip: use JSON_PRETTY_PRINT only under development. In production, the cost of displaying the formatted json can be great due to spaces and line breaks added to the return.

2 answers

3


When sending the character ? alone in one of the variables of data (concatenating the variables into a string URL, as you are doing) jQuery will treat the URL as JSONP and register a callback when Ajax returns the request. As no callback was indicated (because this was not the intention due to the dataType be "JSON"), will result in the mentioned error such as:

parsererror Error: jQuery33100166499243115803_1534312585291 was not called

jQuery created and tried to call a callback jQuery33100166499243115803_1534312585291 that doesn’t exist.

Send the data on data object-shaped, not string-shaped URL:

data: {
   msg: msgenvio,
   type: 'enviaMsg',
   lobby: $('.lobbyid').val(),
   time: $('.time_user').val(),
   nick: $('.nick_user').val()
},
  • Is this way of sending on date the best way? Or only for this type of error?

  • 1

    I believe it’s the best way.

1

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

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

To do this, there are two ways:

  • Use the data, as already explained in the previous reply.
  • Use the function $.param to assemble the parameters of your url.

See how the $.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 the $.param caused the string passed to change completely. This is because the URL encoding is used.

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

Browser other questions tagged

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