jqueryajaxtextareanewlineurlencode

Jquery .val() not returning line-breaks in a textarea


I got problem with line breaks in a textarea.

I get the text with .val() function:

var messageBody = $('#composeInput').val();

This is my ajax request

$.ajax({
    url: 'serverScripts/messages/addMessage.php',
    data: 'messageBody='+messageBody+'&invitedJSONText='+invitedJSONText,
    success: function(){
        //Do something
    }
});

And PHP:

$messageBody = nl2br(mysql_real_escape_string($_GET['messageBody']));

The text:

Hi!

How are you?

Becomes:

Hi! How are you?

If I insert the variable messageBody to an another div-element I can't see any \n is this normal. How do I fix this?


Solution

  • When the data parameter is passed as a string, you must URL encode it yourself:

    'messageBody=' + encodeURIComponent(messageBody) + '&invitedJSONText=' + encodeURIComponent(invitedJSONText)
    

    But it is far more simpler to pass the data parameter as an object; jQuery encodes the data automatically:

    $.ajax({
        url: 'serverScripts/messages/addMessage.php',
        data: {
            messageBody: messageBody,
            invitedJSONText: invitedJSONText
        },
        success: function (data, textStatus, jqXHR) {
            $("#foo").html(data); // <-- did something
        }
    });
    

    PS: instead of nl2br you can set CSS white-space property to pre-line on an element to display newline as newline.