2

According to this answer https://stackoverflow.com/a/2115554/2311074 I thought that whether json_encode stores a linebreak as \n or \r\n depends on the operating system. However I discovered today that I can generate both output with json_encode on the same operating system (Ubuntu).

Consider the example

  <form id='form'>
     <textarea id='amd' name='stuff'></textarea>
  </form> 
  <button id='lol'>Press Me</button>

with jQuery

$( document ).ready(function() {
  $('#lol').click(function(){
    var text = $('#amd').val();

    $.ajax({
          type: "POST",
          url: ajax.php,
          data: {stuff: text}
      });
 });

and the following ajax.php

$text = $_POST['stuff'];
file_put_contents('test.txt', json_encode($text));

now entering the following

enter image description here

will write the following content in text.txt

"this is a \nbreak up"

However, if I change the data attribut in the jQUery script to

data: $('#form').serialize()

then I find the following content in the text.txt

"this is a \r\nbreak up"

Why is serialize() generating this additional \r to my linebreak \n? I am not even using windows.

Adam
  • 25,960
  • 22
  • 158
  • 247
  • Both client and server is Ubuntu? – Mat May 30 '17 at 20:17
  • Why idk, but if thats the case the only solution would be to do: `file_put_contents('test.txt', str_replace( '\r\n', PHP_EOL, json_encode($text)));` – Xorifelse May 31 '17 at 00:55
  • @Mat yes. I use Xampp on ubuntu, so client and server are even identical. I also tried it on a real Ubuntu Server with a different Ubuntu and Win 7 Client, with the same result. – Adam May 31 '17 at 06:40

1 Answers1

4

so the answer is very easy. jQuery serialize() is adding \r\n, because it's developers coded it like this. You can see the code in jquery github. They replace all the occurrences of /\r?\n/g with \r\n.

Mat
  • 2,378
  • 3
  • 26
  • 35