7

I'm trying to use Ajax with JQuery, what I want to do is just send multiline textbox value to php with Ajax.

I'm using that code, it sends txtAnswer value to php, unfortunately, it removes new lines (\n) from data. How can I solve this problem... Thanks in advance.

$.post(
    'post-answer.php', 
     {
        answer: $("#txtAnswer").val(),
        qid: <?= $question_ID ?>
     },
     function (ajaxResponse) {
        $('#answers').html(ajaxResponse)
     }
   );
Kjartan
  • 18,591
  • 15
  • 71
  • 96
  • Where do you get new lines removed? When you receive from the client, or when you output it? – Nathan Jul 26 '09 at 01:15

4 Answers4

7

Try: escape( $("#txtAnswer").val() )

=-)

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
jevel
  • 71
  • 1
  • 1
  • 2
    Escape is deprecated: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/escape – mikemaccana Jun 10 '15 at 20:55
4

I've also encountered this problem. I have a div updating a preview as a user types in a textarea. Here is what I found to work in my situation:

 jQuery('#task_description').keyup(function() {
  jQuery('#pre_description').html(jQuery('#task_description').val().replace( /\n/g, '<br \\>' ));
 }
3

are you sure \n are removed? What happend if you put this in your php file:

<?php
print_r($_REQUEST['answer']);
?> 

using firebug you can see the output and be sure if \n are there or not.

I never hear about jquery or prototype removing \n

remember that if you want to show new lines on html format you need convert them to <br/>. Which I think you are trying to do.

You can use nr2br to do this.

Gabriel Sosa
  • 7,897
  • 4
  • 38
  • 48
2

I'm using .ajax with type:POST and it's saving the new lines for me

justinl
  • 10,448
  • 21
  • 70
  • 88
  • Actually never mind, once I got the type of .ajax request set to POST, it fixed this (using GET does lose the new lines). – justinl Dec 01 '09 at 10:18