I am writing simple AJAX functions to send comments to the server and save them in a mySQL database with php.
The following code seemed to work just fine for my purposes, basic but did his job, until i tried to put a hash symbol (#) in a comment. Inserting this into the text "crashes" my functions, without saving the written text in the database and returning an empty div basically.
This is the ajax call:
function sendComment(n){
var xmlhttp = createAjax();
var text = document.getElementById("f"+n).value;
if (!validation(text))
return false;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
appendComment(n, xmlhttp.responseText);
}
}
...
url = "comments.php?news="+n+"&text="+text;
xmlhttp.open("GET", url, true);
xmlhttp.send();
...
}
Where createAjax simply creates the xmlhttp object for every browser as standard, validation is a function that checks for many symbols like <,>,=,(,),| with a regular expression.
this is the php part:
function insertComment($text, $news){
$conn = dbConnect();
$user = $_SESSION["user"];
$text = nl2br(htmlentities($text));
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO comments(user, news, date, text) VALUES ('".$user."','".$news."','".$date."', '".$text."')";
mysql_query($sql) or die ("Errore in inserimento: ".sql_error());
echo writeSingleComment($user, $date, $text);
mysql_close(conn);
}
It just connects, saves the comment and returns the html code with echo, so that the javascript function can print it.
This works with any text apparently, but I can't get it to work with an hash, am I missing something? Sidenotes, I could simply add the symbol to the validation regular expr., but my point is to "print" it, not just excluding it. Thanks in advance! Sidenote 2, the javascript attaches the comment to a static element.