Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have written a simple JS script, that saves mouse positions in an array, which I then send to a php function via AJAX. It works, and saves the recieved data, but the problem is how it is saved, i.e. i would expect to have a normal output of the x and y position as is: [x1,y1],[x2,y2],[x3,y3],...

But what i get is something like this: a:63:{i:0;a:2:{i:0;i:527;i:1;i:1010;}i:1;a:2:{i:0;i:490;i:1;i:1205;}i:2;a:2:{i:0;i:588;i:1;i:1311;}i:3;a:2:{i:0;i:615;i:1;i:1368;}i:4;a:2:{i:0;i:553;i:1;i:1474;}i:5;...

I thought if i encode it in JSON format that it would save as i thought, but i dont understand why the output is as it is. Any ideas?

The JS code is as follows:

window.onbeforeunload = function() {
  var jsonString = JSON.stringify(tabela);
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: {
            text1: jsonString
        }
    });
}

And the PHP side is this:

    $text1 = json_decode(stripslashes($_POST['text1']));
    $string_data = serialize($text1);
    file_put_contents("your-file.txt", $string_data);
    

share|improve this question
    
You dont stripslashes() a json format unless encoded with JSON_UNESCAPED_SLASHES and never serialize user input as its a security risk. – Xorifelse Jan 15 at 21:40
    
True, sorry, but even if i remove that, it still does not work as expected... – Tadej Bogataj Jan 15 at 21:41
    
As @Rafael says, just store it directly into the file: file_put_contents("your-file.txt", $_POST['text1'] . PHP_EOL); – Xorifelse Jan 15 at 21:45
up vote 0 down vote accepted

The content looks like this in the file, because you passed the array through serialize function. In order to "decode" file content, use unserialize. If you want to have more human-readable file content, just store the JSON string in the file ($_POST['text1'] directly) or instead of serialize use json_encode again before calling file_put_contents.

share|improve this answer
    
Thank you, your anwser helped me. – Tadej Bogataj Jan 15 at 21:45
    
@TadejBogataj you're welcome. Glad I could help. – Rafael Jan 15 at 21:46
    
@TadejBogataj if it helped, have the courtesy to upvote and you can mark it as in answer in 15 minutes after asking your question. – Xorifelse Jan 15 at 21:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.