0

Long story short, I have a textarea and I want to preserve the formatting with the proper line breaks. I'm getting the value of the text area with the following javascript call.

var letterText = document.getElementById("cnl-lettertext").value;

After that I sent it through an Ajax call and rest api to be saved to a database. I can't seem to get it to keep the \r\n characters or line breaks in the variable for some reason when I'm setting it.

I've tried setting white-space: pre on my css for it but that doesn't seem to work. I also don't want to just use .replace because that disrupts other functions.

ajax call:

$.ajax({
    url : url, //url is built dynamically for a rest api.
    timeout : 5000,
    dataType : "json",
    statusCode : {  },
    success : function(data) {
                            
    
    }
});
Maze
  • 368
  • 3
  • 15
  • Please show your Ajax call. I'm guessing you're not encoding the value (with `encodeURIComponent(letterText)` for example), but hard to tell without seeing the code – blex Jun 22 '20 at 17:19
  • https://stackoverflow.com/questions/29574876/line-breaks-not-working-in-textarea-output –  Jun 22 '20 at 17:22
  • @blex I went ahead and added my ajax call. – Maze Jun 22 '20 at 17:33
  • 1
    _"url is built dynamically for a rest api."_ <---- i think your problem might be right here. Try doing `'https://...' + encodeURIComponent(letterText) + '...'` – blex Jun 22 '20 at 17:34
  • Fantastic @blex . That worked like a charm! – Maze Jun 22 '20 at 18:29
  • OK, then I posted an answer to make it better – blex Jun 22 '20 at 18:30

1 Answers1

1

When you send a request to a URL with line breaks, the browser will remove those line breaks, which are not URL-compatible. They need to be encoded.

You could do it manually with encodeURIComponent, but since you're using jQuery, take advantage of it, and pass query parameters the right way, with the data option. They will be encoded correctly by jQuery:

$.ajax({
    url : 'https://www.example.com/endpoint', // don't add query params here
    timeout : 5000,
    dataType : "json",
    data: { // Add them here, they will be encoded automatically
      letterText: letterText,
      // ...
    },
    statusCode : {  },
    success : function(data) {}
});
blex
  • 24,941
  • 5
  • 39
  • 72