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
  • 238
  • 2
  • 14

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
  • 23,736
  • 5
  • 39
  • 70