[英]I want to populate my form elements with data i fetch from my database in another php file using ajax
I am trying to populate my form elements with a row fetched from a database. 我试图用从数据库中获取的行填充表单元素。 I am trying to use ajax to send the id of the row i want to fetch when a button is clicked. 我试图使用ajax发送我想要在单击按钮时获取的行的ID。
I am trying to use ajax. 我正在尝试使用Ajax。 I have successfully retrieved the row i want in the php file but cant send the data back to the requesting page. 我已经成功检索了我想要的php文件中的行,但无法将数据发送回请求页面。
My table has edit and delete buttons for each row. 我的表格的每一行都有编辑和删除按钮。
while ($row = mysqli_fetch_array($result)) {
echo '<tr style="margin:10px;">';
echo "<td>".$row['title']."</td>";
echo "<td>".$row['uname']."<td>";
echo '<td><button class="btn btn-warning" onClick="editBtnClicked('.$row['id'].')">Edit</button><td>';
echo '<td><button class="btn btn-danger" onClick="deleteBtnClicked('.$row['id'].')">Delete</button><td>';
echo "</tr>";
}
And my script looks like this: 我的脚本如下所示:
function editBtnClicked(id) {
$.ajax({
type: 'post',
url: 'edit.php',
data: { edit_id: id },
success: function (data) {
// ...
}
})
}
And my edit.php
file: 和我的edit.php
文件:
$id= $_POST['edit_id'];
$stmt= "SELECT * FROM blog WHERE id=".$id;
$result= $conn->query($stmt);
$rows = $result->fetch_assoc();
I want to send $rows['name']
and $rows['body']
to the page that contains the table and populate a form that has two text areas with it. 我想将$rows['name']
和$rows['body']
发送到包含表的页面,并填充具有两个文本区域的表单。
At the end of your edit.php
file, add this line 在edit.php
文件的末尾,添加以下行
echo json_encode($rows);
Modify your function like this: (I am assuming that your name and body textareas have ids nameTextArea
and bodyTextArea
respectively.) 像这样修改您的函数:(我假设您的姓名和正文textareas分别具有ids nameTextArea
和bodyTextArea
。)
function editBtnClicked(id) {
$.ajax({
type: 'post',
url: 'edit.php',
data: { edit_id: id },
success: function (data) {
console.log(data);
$('#nameTextArea').val(data.name);
$('#bodyTextArea').val(data.body);
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.