我使用以下表格
<form id="dataForm" method="post">
<h2 id="formheader"> Update Description</h2>
<div>
<label>Product Name:</label>
<input class="inputForm" id="orginalName" type="text" name="Name">
</div>
<div>
<label>New Description:</label>
<input class="inputForm" id="newDescription" type="text" name="description">
</div>
<div id="theSubmit">
<button id="editDesButton">Submit</button>
</div>
</form>
</section>
以及以下javascript函数
function editDescription(){
xmlhttp = new XMLHttpRequest();
var name = document.getElementById("orginalName");
var Description = document.getElementById("newDescription");
var data_seen = false;
// this is a flag to record whether any data has been seen. Used in the guard ofthe alert statement.
if (name.value !="" && Description.value !=""){
data_seen = true;
xmlhttp.open("POST","editDescription.PHP",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("Name=" + name.value + "&Description=" + Description.value);
}
if (!data_seen) {
alert("please enter some data");
}
}
submitButton = document.getElementById("editDesButton");
submitButton.addEventListener("click", editDescription);
这个小小的php
$Name = $_POST['Name'];
$Description = $_POST['description'];
if($Name !="" && $Description !=""){
$sql = "UPDATE PRODUCTS SET P_Description = '$Description' WHERE P_NAME = '$Name'";
$conn->exec($sql);
如果我运行表单并使用action="editDescription.php
,则运行sql并将表更新为我想要的方式但是当我在单击按钮时在事件上运行javascript时,值不是传入,我不明白为什么,有没有人有任何指针?
答案 0 :(得分:0)
当您使用提交功能时,浏览器会自行(正确)显示字段。在你的js代码中你不是urlencoding。在大多数情况下,如果您在字段中输入空格或需要编码的任何其他字符,它将会失败。 第二件事,在下面的行中,你必须使用小写&#34; d&#34;为你的&#34;描述&#34;领域。 PHP区分大小写。 (我建议你总是使用小写字段名来避免错误)
尝试:
xmlhttp.send(encodeURI("Name=" + name.value + "&description=" + Description.value));
也许还有更多问题。就像Pierre Emmanuel所说,使用javascript控制台,特别是&#34; Network&#34;选项卡可以直接监视您通过电汇发送的内容。您还可以查看使用var_dump($_POST);
接收的PHP内容。 (或var_dump(file_get_contents("php://input"));
如果第一个命令失败。)
答案 1 :(得分:0)
将您的javascript代码更改为jQuery:
function editDescription(){
var name = $('#orginalName').val(); //getting input field value
var description= $('#newDescription').val(); //getting input field value
$.ajax({//create an ajax request to Your.php
type: "POST",
url: "Your.php", //your php file name
data:{"name ":name,"description":description},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
}
submitButton = document.getElementById("editDesButton");
submitButton.addEventListener("click", editDescription);
Your.php
$Name = $_POST['name'];
$Description = $_POST['description'];
if($Name !="" && $Description !=""){
$sql = "UPDATE PRODUCTS SET P_Description = '$Description' WHERE P_NAME = '$Name'";
$conn->exec($sql);