Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement