Error with mysqli and Ajax data

Asked

Viewed 23 times

0

I’m having a problem fetching data using ajax.

<script>
//função buscar dados
    function buscarDados(id) {
        $(function () {
            $.ajax({
                url: 'ajax/dados_aluno.php',
                type: 'POST',
                data: {id: id},
                success: function (data) {
                    $('#visualizar_aluno').html(data);
                },
                error: function () {
                    alert('Ocorreu um erro com o AJAX');
                }
            });
            return false;
        });
    }
</script>

with this code I get the data in mysqli with php.

<?php

require_once '../../../config/config.php';

//pegar id do aluno
$id = $_POST['id'];

//fazer busca no banco de dados
$sql = "SELECT * FROM alunos WHERE id=$id";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
$nome = $row['nome'];
$obs = $row['obs'];

echo "<script>$('#nome').html('$nome');$('#obs').html('$obs');</script>";

however this error when sending the data of the variable Obs that are data with line break ex: "Hi I am nub, and wanted to know" it returns so when performing the action (making clear that only the name works perfectly, only when there is line break that stops working)

<script>
$('#nome').html('Fulano de Tal');
$('#obs').html('Os dados
estão
quebrados')
</script> 

woe of error and I can’t solve

  • Try trading for veja sobre templates literais https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals, então coloque assim $('#obs').html(Data are broken `)

  • It worked perfectly. Thank you

  • All right, I’ll post as answer then beauty? Oh you accept. Thank you

  • Put that I accept

1 answer

1


To solve this you can use the literals template https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals added to Ecma script 2016. Staying as follows

<script>
$('#nome').html('Fulano de Tal');
$('#obs').html(`Os dados
estão
quebrados`)
</script> 

You can also, if you prefer, add line breaks and concatenate with the "+", thus

<script>
$('#nome').html('Fulano de Tal');
$('#obs').html('Os dados\n' + 
'estão
quebrados')
</script> 

Browser other questions tagged

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