0

I am trying to update data using jquery but it fails in case of textarea having enter in it, which is represented by \r\n in mysql.

my code for update function is.

<td><i class="fa fa-edit" onclick="upd('<?php echo $fetch_news ['title']; ?>',
                                                          '<?php echo $fetch_news ['detail']; ?>',
                                                          '<?php echo $fetch_news ['date']; ?>',
                                                          '<?php echo $fetch_news ['id']; ?>'
                                                          )"></i></td>

and my update function is

function upd(title,detail,date,id)
{
  $("#newsTitle").val(title);
  $("#newsDetails").val(detail);
  $("#newsDate").val(date);
  $("#id").val(id);
}

my text area input is

<div class="form-group"><textarea id="newsDetails" name="newsDetails" title="News Location (less than 200 words)" placeholder="News Details (less than 200 words)" required="" class="form-control"></textarea></div>

this code works fine if there is no enter pressed while inserting textarea data

the error i get is

Uncaught SyntaxError: Invalid or unexpected token

my insert function is

$(function () {
      $("#form").on("submit", function(){
            $.ajax({
                url: "extra/logical.php?pg=news&tsk=ins",
                type: 'POST',
                data: new FormData(this),
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                  $("#showdata").html(data);
                  $("#newsTitle").val('');
                  $("#newsDetails").val('');
                  $("#newsDate").val('');
                  $("#id").val('');
                }
            });
            return false;
        });
    });

and insert query is

$ins="insert into news set title='".$_POST['newsTitle']."',
                                        detail='".$_POST['newsDetails']."',
                                        date='".$_POST['newsDate']."'
                                        ";
        mysqli_query($conn,$ins);

Any help will be appreciated.

7
  • Use htmlspecialchars before saving into database, also, could you show the code of saving into MySQL? Commented Jul 31, 2018 at 18:29
  • The issue is the fact the enter is being added in the HTML markup so it is adding an enter into your event listener.... You need to escape it. Commented Jul 31, 2018 at 18:30
  • @MyLibary see code of saving into MySQL. I updated Commented Jul 31, 2018 at 18:35
  • @epascarello how to escape this Commented Jul 31, 2018 at 18:36
  • stackoverflow.com/questions/13709517/… Commented Jul 31, 2018 at 18:37

2 Answers 2

0

First of all, @epascarello is correct in stating that you need to escape all data going into your database. You are also doing it in an extremely unsafe way, guaranteed to be hacked. Creating your SQL-statements that way opens your code up for something called SQL Injection, and is probably the most common way a website is hacked.

You need to use prepared statements and safeguard your code saving the data, as well as encode the data going in.

As per the examples in this guide and the explanations given there, PDO is the only safe way to handle user input that is being saved to a database. This is because of the way the prepared statements are prepared on the database server, before you put your data into the query.

As for code, look at this for saving the data:

$host = 'localhost';
$db   = 'myDatabase';
$username = 'awesomeUser';
$pass = 'someTotallySecretPassword';
$charset = 'utf8';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

$opt = [ PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];

$pdo = new PDO($dsn, $username, $password, $opt);
$stmt = $pdo->prepare('INSERT INTO news SET title = :title, details = :details, date = :date');
$stmt->execute([
    'title' => urlencode($_POST["newsTitle"]), 
    'details' => urlencode($_POST["newsDetails"]),
    'date' => $_POST["newsDate"]
]);
$user = $stmt->fetch();

I am going to advice you to also create the date yourself, on the server, either in SQL or in PHP, unless your use case needs the user to be able to insert a date different than the creation time of the news-article you are creating. If the user does have a need to insert an arbitrary date, you need to do some validation on that as well, to make sure it is valid.

Now, when you need to get the data out again, you need to decode the data from the database with javascript:

function decode(text)
{
    return decodeURIComponent(text.replace(/\+/g,' '));
}

function upd(title,detail,date,id)
{
  $("#newsTitle").val( decode(title) );
  $("#newsDetails").val( decode(detail) );
  $("#newsDate").val( date );
  $("#id").val( id );
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for such a useful info. I will work on it. Also tell me what if i use mysqli_real_escape_string() while insertion instead of PDO.
@AnilSangwa Well, it IS better, but still open to some exploits. Prepared statements are preprocessed by the server, and that ensures that the query itself cannot be altered simply by inserting text. And altering the query is the heartbof sql injections.
my database connection is $conn=mysqli_connect('localhost','root','password','lucentsapi') or die('failed to connect'); what do i need to change this? if so, why?
@AnilSangwa If you look at the code sample I gave you, you can see the variables that make up the information in your connection string. $host = 'localhost'; $username = 'root'; $password = 'password'; $db = 'lucentsapi';
Will implement and let you know
|
0

You can prevent the default action of pressing enter in the textarea with an event listener.

<textarea placeholder="You can not press enter"></textarea>
<script>
document.querySelector("textarea").addEventListener("keypress", function(e){
  if(e.keyCode==13){
    e.preventDefault();
  }
});
</script>

On the server-side, with PHP, you should replace all the line breaks with an empty String so the insertion will not fail (from this answer).

str_replace("\r\n", "", "your insertion statement string");  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.