3

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?

Salman A
  • 262,204
  • 82
  • 430
  • 521
einstein
  • 13,389
  • 27
  • 80
  • 110

3 Answers3

14

When you pass a string as the data parameter, you must URL encode it like this:

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

If you pass the parameters as an object, jQuery takes care of encoding the data:

$.ajax({
    url: 'serverScripts/messages/addMessage.php',
    data: {
        messageBody: messageBody,
        invitedJSONText: invitedJSONText
    },
    success: function (data, textStatus, jqXHR) {
        $("#foo").html(data); // <-- did something
    }
});
Salman A
  • 262,204
  • 82
  • 430
  • 521
0

Is not that a known issue? http://api.jquery.com/val/

The workaround is using valHooks as explained in the Note section.

pranay
  • 444
  • 1
  • 7
  • 20
0

You may want to look at PHP's nl2br function. Newlines characters do not render in the browser, so you have to replace them with line breaks.http://us.php.net/nl

kobe
  • 15,671
  • 15
  • 64
  • 91