Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea .val No Line Breaks when Sending Data via Ajax

I have seen a ton of articles about how to add line breaks to the .val, but none of them seem to be working for me. I have tried the jQuery recommended workaround:

$.valHooks.textarea = {
  get: function( elem ) {
  return elem.value.replace( /\r?\n/g, "\r\n" );
  }
};

but, no matter what I seem to do, the text still gets smashed together into one line.

Here is my code:

HTML:

 <div id="email-info">
    <div id="email-top-row">
        <div id="email-subject-container">
            <label for="email-subject" class="email-labels">Subject:</label>
            <input id="email-subject"></input>
        </div>
        <div id="email-from-container">
            <label for="email-from" class="email-labels">From:</label>
            <input id="email-from"></input>
        </div>
    </div>

    <div id="email-body-container">
        <label for="email-body" class="email-body">Body:</label>
        <textarea id="email-body"></textarea>
    </div>
    <button id="email" onclick="emailSend()">Send Email</button>
</div>

Javascript:

function emailSend() {
 $.valHooks.textarea = {
  get: function( elem ) {
  return elem.value.replace( /\r?\n/g, "\r\n" );
  }
 };

 var emailSubject = $('#email-subject').val();
 var emailFrom = $('#email-from').val();
 var emailBody = $('#email-body').val();        

 emailURL = emailURL + '&email_subject=' + emailSubject;
 emailURL = emailURL + '&email_from=' + emailFrom;
 emailURL = emailURL + '&email_body=' + emailBody;

 $.getJSON(emailURL, function(data) {
    console.log(data);
 });
}

Now, say I add this to the textbox:

test line 1

test line 2

test line 3

When I do a console.log of that, it comes out in the console correct with the line breaks, but in the network inspector tab, and on our server, what is sent is test line 1test line 2test line 3.

I am kinda at a loss of how to add in the line breaks to the url. I have seen a lot of stuff about the '\n' but I have never seen that in my url or in my console logs.

Any help would be greatly appreciated. Thank you very much.

like image 520
David Avatar asked Jan 26 '15 19:01

David


1 Answers

you need to escape your values coming from your textbox before appending to your url:

var emailSubject = encodeURIComponent($('#email-subject').val());
var emailFrom = encodeURIComponent($('#email-from').val());
var emailBody = encodeURIComponent($('#email-body').val());
like image 169
Patrick Gunderson Avatar answered Sep 27 '22 20:09

Patrick Gunderson