如何使用AJAX和PHP将数据添加到sql db中

I have 2 input fields "User" and "Comment" and I want the user input to be saved asynchronously using AJAX, so no refreshing. So far I've gotten it to add a new row to the DB, but for some reason it is empty. I believe the reason is I am not appending the values correctly.

HTML(JS is in-between head tags):

<p>User: <input type="text" id="userName" /></p>
<p>Comment : <input type="text" id="comment" /></p>
<input type="button" value="Submit" onclick="callServer();" />

JS:

function callServer(){
  var usr = document.getElementById("user").value;
  var cmnt = document.getElementById("comment").value;
  var ajaxRequest = XMLHttpRequest();

  ajaxRequest.open("POST", "insert.php", true);
  ajaxRequest.send(null);
}

PHP:

<?php
// Setting variables for the elements
$user = $_POST['user'];
$comment = $_POST['comment'];

// Establishing connection and selecting db    
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db('local',$con);

// Doing the query for the insert
$query = mysql_query("INSERT INTO content (Title, Article)
VALUES('$user', '$comment')");

mysql_query($query, $con);
mysql_close($con);
?>

Your input ID is userName but you are targeting user.

Change to:

var usr = document.getElementById("userName").value;

You are also sending null with the ajax request, you should be sending your data:

var params = "user=" + encodeURIComponent(usr) + "&comments=" + encodeURIComponent(cmnt);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
ajaxRequest.send(params);

Also, you should include the content-type header - as above.

Finally, the mysql_* library is deprecated, you should use a modern API such as PDO or MySQLi for any new development. Because you're using this library you need to escape post data for SQL Injection:

$user = mysql_real_escape_string($_POST['user']);
$comment = mysql_real_escape_string($_POST['comment']);

If you use a modern API, you can do parameterised queries which don't require you to manually escape anything.

Also just noticed, remove this line:

mysql_query($query, $con);

You have already executed the query on the line before that. This line is useless and will fail, it is trying to execute another query using the result resource of the first query.

I'd start looking a little into Jquery, it helps a lot on the javascript/Ajax part.

The problem here is that you are never sending the variables in the AJAX call, you need something like this:

ajaxRequest.send(postvariables);