I am trying to create a comment system for a website using ajax php and mysql. For this I want to send the id of the button clicked to upload a comment (Which will be set to the article name) to an sql database (as well as the comment and some other stuff…)
The system I have at the moment is being rather strange.. If I copy it into jsFiddle it and link to the correct php file on my server it works fine and the id of the button is uploaded to the database.. However if I upload the exact same thing to my website it doesn’t work… Here’s what I have:
Html form:
<form id="addCommentForm">
<input type="email" name="email" onchange="checkEmail();" id="email" /> </br>
<div>
<p id="emailerror"> </p>
</div> </br>
<input type="text" name="username" id="username" /> </br>
<input type="text" name="content" id="content" /> </br>
<input type="Button" value="submit" id="Test" onclick="commentSend(this.id);return false;"/>
</form>
The javascript (external):
function commentSend(clicked_id)
{
var email = document.getElementById("email").value //gets the user's email
var username = document.getElementById("username").value //gets the user's username
var content = document.getElementById("content").value //gets the comment content
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttp.open("GET","commentUpload.php?email=" + email + "&username=" + username + "&content=" + content + "&articleName="+ clicked_id,true);
xmlhttp.send();
return false;
}
And the php:
<?php
$con = mysql_connect("myserver","myusername","mypassword");
mysql_select_db("mydatabase", $con);
$articleName = mysql_real_escape_string($_GET['articleName']);
$email = mysql_real_escape_string($_GET['email']);
$username = mysql_real_escape_string($_GET['username']);
$content = mysql_real_escape_string($_GET['content']);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$query = "INSERT INTO Comments (id, article, email, name, body) VALUES (NULL, '" . $articleName ."', '" . $email ."', '" . $username . "', '". $content . "')";
mysql_query($query);
mysql_close($con);
?>
The only thing I can possibly think of is that there is some error with passing the variable this.id to an external javascript file because this is the only value that doesn’t get uploaded to the database…
Anyone any ideas!?
You are not encoding your variables for use in a query string.
What you can do to solve that, is using
encodeURIComponent(for all values…) like: