Home » Php » php – remove new line when sending request to server via Ajax Post with JQuery

php – remove new line when sending request to server via Ajax Post with JQuery

Posted by: admin July 12, 2020 Leave a comment

Questions:

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)
     }
   );
How to&Answers:

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

=-)

Answer:

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 \>' ));
 }

Answer:

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.

Answer:

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