1

I have data written to an html file via PHP like so:

$data = json_decode(stripslashes($_POST['data']));

if($data[0]!=''){
    $_SESSION['chatCode'] = $data[2];

    $fp = fopen('../sessions/chats/log_'.$data[2].'.html', 'a');

    $content = array(
        'author' => $data[1],
        'message' => $data[0],
        'time' => date('H:i:s'));

    fwrite($fp,serialize($content));
    fclose($fp);
}

However, I am struggling to parse the serialized data client-side in jQuery. My current code is this:

$.get('sessions/chats/log_'+chatCode+'.html', function(data){
    $('#chatContent').html(makePretty(data));
}

function makePretty(html){
    var data = JSON.stringify(html);

    console.log(data);

    var content = '';

    for(i=0; i < data.length; i++){
        content += '<div class="msgln">'+
            '<div class="meta">'+
                '<span class="name">'+data[i]['author']+'</span>'+
                '<span class="time">'+data[i]['time']+'</span>'+
            '</div>'+
            '<div class="msg">'+data[i]['message']+'</div>'+
        '</div>';
    }

    return content;
}

The log file log_test.html contains:

a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"09:23:23";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"09:26:39";}a:3:{s:6:"author";s:5:"e297f";s:7:"message";s:4:"test";s:4:"time";s:8:"09:37:03";}

The console logs:

"a:3:{s:6:\"author\";s:5:\"e297f\";s:7:\"message\";s:4:\"test\";s:4:\"time\";s:8:\"09:23:23\";}"

2
  • 1
    It's quite odd to save arrays in a html document. Commented May 26, 2015 at 8:43
  • The client wanted the logs saved in a local file - it was either html or txt and I've saved logs to html in the past so it seemed the obvious choice. Having second thoughts now! Commented May 26, 2015 at 8:45

2 Answers 2

1

Thats because you're serialize($content) data and writing it. Instead try json_encode($content) and write it. That should work with your current jQuery code.

Change

fwrite($fp,serialize($content));

To

fwrite($fp,json_encode($content));
Sign up to request clarification or add additional context in comments.

Comments

0

Writing serialized array is bad practice you mush use json_encode for saving data into file:

fwrite($fp,json_encode($content));

and while getting data in ajax, instead of using JSON.stringify use:

JSON.parse(dataString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.