我用这个AJAX发送了两个数据到我的PHP:
function ajax_post(){
// Create our XMLHttpRequest object
var request = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "php/addUser.php";
var username = document.getElementById("newUserName").value;
var password = document.getElementById("newUserPass").value;
var newUsername = "user_name="+username;
var newPassword="password="+password;
request.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
document.getElementById("output").innerHTML = return_data;
}
};
// Send the data to PHP now... and wait for response to update the status div
request.send({newUsername,newPassword}); // Actually execute the request
这是PHP代码,它应该将这两个数据插入我的mysql数据库。
//Connect to the database
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
$userName=$_POST['newUsername'];
$userPassword=$_POST['newPassword'];
$query="INSERT INTO users(user_name,password)
VALUES('$userName','$userPassword')";
if ($connection->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $connection->error;
}
$connection->close();
运行AJAX时,它运行时没有错误,并将数据发送到我服务器上的PHP代码。然后PHP代码运行并完成,没有错误,但是当我检查我的数据库时,新用户被插入到数据库中,但它是空的。我很确定这是我的PHP代码中的东西,但我还没想到它。
答案 0 :(得分:1)
request.send()
的参数应该是URL编码的字符串,而不是对象。
request.send(newUsername + '&' + newPassword);
请注意,在设置变量时也应使用encodeURIComponent
,以防它们包含特殊的URL字符。
var newUsername = "user_name=" + encodeURIComponent(username);
var newPassword = "password=" + encodeURIComponent(password);
此外,您的对象语法不正确。对象的语法是
{ prop1: value1, prop2: value2, ... }
{ var1, var2 }
应该给你一个语法错误。
您还使用了错误的$_POST
键。键应与=
之前的参数名称匹配,而不是表单字段的ID。
$userName = $_POST['user_name'];
$userPassword = $_POST['password'];
您还应该在PHP中使用预准备语句而不是变量替换,以防止SQL注入问题。
$query = "INSERT INTO users (user_name, password) VALUES (?, ?)";
$stmt = $connection->prepare("ss", $userName, $userPassword);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $stmt->error;
}
$connection->close();
答案 1 :(得分:0)
您使用ajax发布user_name
和password
。但在您的PHP代码中,您使用了$_POST['newUsername']
和$_POST['newPassword']
。您可以更改ajax或PHP。
例如:
$userName = $_POST['user_name'];
$userPassword=$_POST['password'];
你的ajax请求应该是
request.send(newUsername+"&"+newPassword);