[英]Using Ajax how can I match a input value from a form to records in my database and fetch associated record/row to prefill a form?
[英]How can i use a value from a form input to match in my database and fetch record/row data to prefill a form?
我有一个名为“ invoiceidcopy”的表单输入...我需要将此输入值的值与数据库中该列(invoiceidcopy)下的值相匹配,然后获取其关联的记录/表单数据行以进行预填充我点击“#submit-id”按钮时的表单。
我的表单和数据库具有以下名为“发票发票”,“位置”,“ q1”,“子检查”的输入/列。
以下是我所能达到的最大距离。
非常感谢,并感谢任何人的提前帮助。
形成
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="/xxx.php">
<input id="invoiceidcopy" name="invoiceidcopy" type="text" value="XXXIDXXX"/>
<button id="submit-id">Prefill Form</button>
<input id="location" name="location" required="" type="text">
<input type="radio" id="q1" name="q1" value="4.99" checked="checked">
<input type="radio" id="q1" name="q1" value="7.99" />
<input id="subcheck" name="subcheck" value="0" type="hidden">
<input id="subcheck" name="subcheck" value="1" onclick="return false" checked="" type="checkbox">Agree to Terms of Service
<button id="btn1" type="submit" name="Submit">Submit</button>
</form>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(function(){
$('#submit-id').on('click', function(e){ // Things to do when '#submit-id' button is clicked
var invoiceidcopy = $('#invoiceidcopy').val(); // Grab user invoiceidcopy from text field
e.preventDefault(); // Prevent form from submit, we are submiting form down with ajax.
$.ajax({
url: "/tst/orders2.php",
data: {
'invoiceidcopy':invoiceidcopy
}
})
.done(function(data) {
data = JSON.parse(data);
$('#location').val(data.location);
$('#q1').val(data.q1);
$('#subcheck').val(data.subcheck);
});
});
});
</script>
</body>
</html>
/tst/orders2.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['invoiceidcopy']))
{
$invoiceidcopy= $_GET['invoiceidcopy'];
$query = "SELECT location, q1, subcheck
FROM seguin_orders
WHERE invoiceidcopy = '".($invoiceidcopy)."'";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($result)){
echo json_encode($row);
die();
}
?>
您的代码在文本字段和单选/复选框中将正常工作...但是.val()
将设置单选/复选框的值
要在选中和未选中...等之间切换,您可能需要使用.attr()
或.prop()
并根据预填充值按要求设置checked
$("#q1").attr('checked', true);
$('#subcheck').prop('checked', true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.