Me and a friend are trying to make a commenting system for our website, We have a somewhat simple bit of code to insert values into a mysql database to then later be read and displayed as comments, however the data is not sending correctly to the table at the moment. We are both fairly new to ajax, php and mysql so it may be just a stupid mistake! 😛
The html:
<form id="postComment" action="Comments.js" method="post">
<input type="email" name="email" onchange="checkEmail();" id="email" /> </br>
<div id ="emailerror">
<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" onclick="commentUpload();" />
</form>
The Javascript file:
function commentUpload() //uploads comment to sQl table
{
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 articleName = document.getElementById("articleName") gets the article name
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,true);
xmlhttp.send();
}
And the php:
<?php
$email=mysql_real_escape_string($_GET['email']);
$username=mysql_real_escape_string($_GET['username']);
$content=mysql_real_escape_string($_GET['content']);
$query="INSERT INTO Comments
VALUES (1, email, username, content)";
mysql_query($query);
mysql_close();
?>
Thanks for any help in advance!
So this may be me, but I would suggest you don’t use any javascript when adding or uploading the comments; ajax can provide some wonderfully powerful code, but it’s probably be better to use it when querying from the database on the clientside as opposed to inserting to the database on the serverside!
You HTML code should instead jump directly to the PHP, as opposed to being transitioned through the AJAX as you had previously programmed. And instead of using some javascript to change between $_POST and $_GET, you can simply change the method in the HTML.
Next, you must be sure to include a connection to your database. w3Schools has a nice tutorial on establishing connections. At the same time, you must also be sure to concatenate your parameters that you got from the $_GET into the query string using periods.
I hope that helped! Best of luck with the rest of the website!