Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
unwanted leading space inside data from a table column

a column named story is a text type
clicking on a button I have a jquery ajax to get data from that column - on a specific id

<div id='bstory'></div>

on server side I have:

function a_click($id){
    global $db;
    $sq = "select story from dict where id = :aid limit 1";
    $st = $db->prepare($sq);
    $st->execute([":aid" => $id]);
    echo $st->fetchColumn();
}

on client side:

$(document).on('click', '.atitle', function(){
    let id = $(this).attr('data-id');
    $.post('a_dict_pro.php', {fn: 'a_click', args: [id]}, function(data){
        console.log(data);
        $(bstory).text(data);
    });
});

everything works
problem - there is a leading space before data
on both places - bstory and console
for example if column content is lorem ipsum (without space) - I'm getting lorem ipsum (with space)
if I write data = data.trim() - there is no the space
I'm sure there is no that space inside the table column
pls help

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I will try to explain the problem you have. When your PHP code is executed you may have some empty spaces, lines and other symbols before echoing and after echoing the output. The will be returned. So the things you should do is to assure you don't have any spaces or lines before the <?php tag and to exit immediately after echoing your response i.e. something like echo $st->fetchColumn(); exit; or similar.

All this inconveniences could be saved if you output your result as a JSON string i.e. convert your fetched DB row to JSON string and set response headers to application/json; Than your data will be actually an Array or Object and during the JSON decode which will be made automatically by $.post even if you have spaces or other so called empty symbols they will be automatically stripped or ignored. For the JSON parser there's no significant difference if the string is {} or it is {} ;

I hope I described it well.

Now you know why passing a JSON as response is better than passing a simple string.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda