3

The $_POST['reply'] variable contains html tags like <p>text goes here</p> but I can not insert it into the database. For the reply I use the TinyMCE and when I do not use it (the input as no tags) like text goes here then it is inserted correctly.

What am I missing here?

try {
    $db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->prepare("INSERT INTO replies(article_id, comment) VALUES (:article_id, :comment)");

    $stmt->bindParam(':article_id', $article_id, PDO::PARAM_INT);
    $stmt->bindParam(':comment', $_POST['reply'], PDO::PARAM_STR);


    if($stmt->execute()) {
      echo 'success';  
    }

    $db = null;
} catch(PDOException $e) {
    trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}

Here is the form code:

<form class="comment-form">
    <div class="form-input">
        <input type="hidden" name="post_id" value="<?= $row['id']; ?>" />
    </div>

    <div class="form-input">
        <textarea name="reply" id="elm1" rows="8"  placeholder="Your comment here" ></textarea>
    </div>

    <div class="form-input">
        <input type="Submit" class="btn btn-primary" id="submit" value="SEND" />
    </div>
</form>

<script type="text/javascript">
    $(function(){
        $(".comment-form").submit(function(event){
            event.preventDefault();
            $("#results")
                .show();

            $.post('add-it.php', $(".comment-form").serialize(), function(data) {
                $('#submit')
                    .hide();
                $('#results')
                    .html(data)
                    .fadeIn('slow');
            });
        });
    });
</script>
jvperrin
  • 3,368
  • 1
  • 23
  • 33
EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179

5 Answers5

6

Since you use AJAX, you need to manually trigger saving function in TinyMCE. And that needs to be done, before you send a request.

 $("#results").show();
     tinyMCE.triggerSave(); // <--- Add this here
    $.post('add-it.php'....

And this absolutely has nothing to do with PDO. You could simply do print_r($_POST) to see if data comes, before inserting a record to a table.

Yang
  • 8,580
  • 8
  • 33
  • 58
3

You can use

$pdo->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);

instead of bindParam this should insert your html code.

And you should set post as method to your form

<form action="#" method="post" class="comment-form">
</form>

And the next one that you should remove your javascript code and test it without and with a normal form to test your problem.

Then main problem is that you $_POST variable is empty its not a PDO problem.

And the last one if your send your request with Ajax you have to call the

tinyMCE.triggerSave();

http://www.tinymce.com/wiki.php/API3:method.tinymce.triggerSave

function ins TinyMCE otherwise your post variable is empty.

René Höhle
  • 26,716
  • 22
  • 73
  • 82
2

I think your issue is that TinyMCE doesn't bind it's changes to the textarea automatically. You need to call tinyMCE.triggerSave() in your submit handler. See When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database.

I have attached a full code sample, which I can confirm works.

<?php

define('DB_DRIVER', 'mysql');
define('DB_DATABASE', 'test');
define('DB_SERVER', '127.0.0.1');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');

try {
    $db = new PDO(
        DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER,
        DB_USER,
        DB_PASSWORD,
        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")
    );
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->prepare("
              INSERT INTO replies(article_id, comment) 
              VALUES (:article_id, :comment)");

    $stmt->bindValue(':article_id', $_POST['article_id'], PDO::PARAM_INT);
    $stmt->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);


    if ($stmt->execute()) {
        echo 'success';
    }

    $db = null;
} catch (PDOException $e) {
    trigger_error('Error occurred while trying to insert into the DB:' 
      . $e->getMessage(), E_USER_ERROR);
}
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>tinymce.init({selector: 'textarea'});</script>
<form class="comment-form">

    <div class="form-input">
        <input type="hidden" name="article_id" value="1"/>
    </div>

    <div class="form-input">
        <textarea name="reply" id="elm1"></textarea>
    </div>

    <div class="form-input">
        <input type="Submit" class="btn btn-primary" id="submit" value="SEND"/>
    </div>

</form>
<div id="results">
    Results
</div>

<script type="text/javascript">
        $(function () {
            $(".comment-form").submit(function (event) {
                event.preventDefault();
                $("#results").show();
                tinyMCE.triggerSave();
                $.post('add-it.php', $(".comment-form").serialize(),
                function (data) {
                    $('#submit').hide();
                    $('#results').html(data).fadeIn('slow');
                });
            });
        });
</script>
CREATE TABLE `replies` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `article_id` int(11) DEFAULT NULL,
  `comment` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
Community
  • 1
  • 1
Ryan
  • 4,594
  • 1
  • 32
  • 35
2

I have taken your code and played with it quite a bit and I think I have been able to sort it for you hopefully, I have changed the $(".comment-form").serialize() for adding the data manually. I have also added tinymce.get('elm1').getContent() as this will retrieve the data thats inside the TinyMCE textarea.

<script type="text/javascript">
    $(function(){
        $(".comment-form").submit(function(event){
            event.preventDefault();
            $("#results")
                .show();

            $.post('add-it.php', {
                post_id: $( '.post_id' ).val(),
                reply: tinymce.get('elm1').getContent()
            }, function(data) {
                $('#submit')
                    .hide();
                $('#results')
                    .html(data)
                    .fadeIn('slow');
            });
        });
    });
</script>
TheSk8rJesus
  • 418
  • 2
  • 12
2

I think an idea for a solution is provided in this question HTML Tags stripped using tinyMCE. Try to use a simple textarea and check if html is posted correctly and saved to the database. This way you will have another clue if this is a fault server-side or client-side. Also try this http://jsfiddle.net/PGtPa/172/ to check your serialized output.

textarea_value -> <p>do this do that</p>
serialized_value -> %3Cp%3Edo+this+do+that%3C%2Fp%3E

jQuery serialize is url-encoding output so check if there is conflict with tinymce settings regarding that part. Also if mod_security is giving you issues you could try to base64 encode textarea value with javascript before posting and base64 decode server-side to get your real value back. For base64 and javascript check this https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding which have a nice example if you use utf8.

Community
  • 1
  • 1