开发者

jQuery AJAX POST New Line

开发者 https://www.devze.com 2022-12-18 05:47 出处:网络
So on our site we currently have a textarea for commenting on certain items. The site uses AJAX so the user can press the button and see their message fade in (Imagine a Facebook style commenting.)

So on our site we currently have a textarea for commenting on certain items. The site uses AJAX so the user can press the button and see their message fade in (Imagine a Facebook style commenting.)

The jQuery/AJAX:

$(function() {
$("input#comment_submit").click(function() {
var comment = $("#comment_box").val();
var dataString = 'comment=' + comment;
$.ajax({
type: "POST",
url: "app.php?id=<?php echo $id; ?>",
data: dataString,
success: function() {
$("textarea#comment_box").attr("disabled", "disabled")
$("input#comment_submit").attr("disabled", "disabled").val("Comment Submitted!");
$("#comments").prepend("<div class=\"comment new\"></div>");
$(".new").prepend("<a href=\"profile.php?username=<?php echo $_SESSION['username']; ?>\" class=\"commentname\"><?php echo $_SESSION['username']; ?></a><p class=\"commentdate\"><?php echo date("M. d, Y", time()) ?> - <?php echo date("g:i A", time()); ?></p><p class=\"commentpost\">" + comment + "</p>").hide().fadeIn(1000);
}
});
return false;
});
});

The PHP:

if (isset($_POST['comment']))
{
$username = $_SESSION['username'];
mysql_query("INSERT INTO appcomments (app_id, username, comment, date) VALUES ('" . $id . "', '" . $username . "', '" . $comment . "', NOW() )");
}

Also, I'm not sanitizing because it's a local copy and I'm trying to get this bug out of the way.

Now, I'm having a severe problem with this. Say a user simply submits this comment:

I enjoyed this

It comes up empty when the page fetches it. I checked the database and the comment was left completely empty.

So that's kind of an odd phenomenon. However, i开发者_运维百科f I addslashes to the $comment when it goes into the database...

if (isset($_POST['comment']))
{
$username = $_SESSION['username'];
$comment = addslashes($_POST['comment']);
mysql_query("INSERT INTO appcomments (app_id, username, comment, date) VALUES ('" . $id . "', '" . $username . "', '" . $comment . "', NOW() )");
}

The previous comment saves to the database.

Now this brings up even more problems. I try to add a line break like so,

I enjoyed this

I hope there are more games like this

Which works, but when I go and try this:

I enjoyed this

I hope there are more games like this

Oh and you rock

That submits a blank into the database.

Lastly, adding an Ampersand into any comment submits a blank.

So at this point I have no clue what to do with my commenting code to fix this. Any help would be accepted and would be much appreciated!


Try using mysql_real_escape_string before pushing it into the DB


Instead of

data: dataString,

do

data: {comment: comment},

If you wanted to continue doing it the way you are doing it now, see encodeURIComponent()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号