[英]Send PHP POST using Javascript AJAX
我的数据未插入数据库,控制台日志和网络收到空白响应。 我有点迷路,我的javascript源代码与其他堆栈溢出答案以及我的PHP代码混合在一起。
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<input type="submit" value="Submit" name="nameSubmit">
</form>
<script>
document.querySelector('#requestForm').addEventListener('submit', postRequest);
function postRequest(e){
e.preventDefault();
const params = {
fName: document.querySelector('#name').value,
fAddress: document.querySelector('#address').value,
fComment: document.querySelector('#comment').value,
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'addRequest.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
</body>
这是PHP代码:
require_once 'Database.php';
var_dump($_POST); // returns `array(0) {}`
if (isset($_POST['nameSubmit'])) {
var_dump($_POST); // shows no response
$r = $_POST['fName'];
$o = $_POST['fAddress'];
$p = $_POST['fComment'];
$query = "INSERT INTO user_request(name, address, comment) VALUES(?,?,?)";
$stmt = $db->prepare($query);
$insert = $stmt->execute([$r, $o, $p]);
if($insert){
echo 'Success';
}else{
echo 'Error';
}
}
我相信post参数nameSubmit
不存在。
使用var_dump()
函数转储所有$_POST
我认为,唯一给出的参数是
为什么不检查请求方法呢?
这比检查变量是否存在更好。 确定这是POST请求后,您可以稍后检查必需的参数。
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Do whatever you want when POST request came in
}
更新:
这是您想要的答案!
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<button onclick="sendData();" type="button">Submit</button>
</form>
<div id="testdiv"></div>
<script>
function sendData(){
var data = new FormData();
data.append('fName', document.getElementById("name").value);
data.append('fAddress', document.getElementById("address").value);
data.append('fComment', document.getElementById("comment").value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php', true);
xhr.onload = function () {
if(xhr.status !== 200){
// Server does not return HTTP 200 (OK) response.
// Whatever you wanted to do when server responded with another code than 200 (OK)
return; // return is important because the code below is NOT executed if the response is other than HTTP 200 (OK)
}
// Whatever you wanted to do when server responded with HTTP 200 (OK)
// I've added a DIV with id of testdiv to show the result there
document.getElementById("testdiv").innerHTML = this.responseText;
};
xhr.send(data);
}
</script>
</body>
PHP代码:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
var_dump($_POST);
}else{
header('HTTP/1.0 403 Forbidden');
}
?>
要添加另一个字段,请在data
var下面添加另一个data.append
函数。
提交按钮必须被选中。 要允许使用enter,请为其添加事件监听器!
我的样子是什么: https : //image.ibb.co/gfSHZK/image.png
希望这是您想要的答案。
两个问题:
1.)由于缺少序列化,参数无法正确发送/根本没有发送。 当您使用表单内容类型时,您的params对象需要采用特定的格式name=value&name2=value2
。 因此,为方便起见,您需要使用以下方法来转换对象:
function getReadyToSend(object) {
var objList = [];
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
objList.push(encodeURI(prop + '=' + object[prop]));
}
}
return objList.join("&");
}
因此,您的发送成为: xhr.send(getReadyToSend(params));
2)您的php期望发送“提交”按钮。 if (isset($_POST['nameSubmit'])) {
您没有发送名为nameSubmit
的变量,则可以通过包含它来解决此问题,或者检查是否设置了每个变量。 我建议后者使用这种方法,如果不传递1个或多个,则可以错误处理。
建议:更新您的加载以检查状态:
if (xhr.status === 200)
{
console.log(xhr.responseText);
}
else if(xhr.status !== 200)
{
console.log('Request failed. Returned status of ', xhr.status);
}
小提琴示例: http : //jsfiddle.net/qofrhemp/1/ ,打开“网络”选项卡并检查呼叫,您现在将在表单数据中看到参数,这些参数表示在单击提交后触发的呼叫。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.