Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.serialize() method adding \r to linebreak?

Tags:

jquery

php

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.

like image 920
Adam Avatar asked Dec 06 '25 10:12

Adam


1 Answers

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.

like image 66
Mat Avatar answered Dec 07 '25 23:12

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!