Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda