我创建了一个网页,该网页使用JQuery将表单内容重定向到另一个网页,使用PHP连接到数据库以查找某些内容。不幸的是,表单的内容传输不正确,因为我收到“通知:未定义的索引:第8行的C:\ wamp \ www \ mywebsite \ target.php中的postal_code”
我的代码:
home.html的
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form action="/" id="myform">
<input type="text" name="postal_code" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$('#myform').submit(function() {
var url = 'target.php';
var postal_code = $('#postal_code').val();
$.post( url, { postal_code: postal_code },
function( data ) {
$( "#result" ).empty().append( data );
}
);
return false;
});
target.php
<?php
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', '', $pdo_options);
$response = $bdd->prepare('SELECT city FROM city_list where postal_code = ?');
$response->execute(array($_POST['postal_code']));
echo '<ul>';
while ($data = $response->fetch())
{
?>
<br/>The city you entered the postal code is : <?php echo $data['city'];
}
$response->closeCursor();
}
catch (Exception $e)
{
die('Error : ' . $e->getMessage());
}
?>
答案 0 :(得分:3)
您正在搜索$('#postal_code').val();
,但postal_code的输入没有ID。
替换
<input type="text" name="postal_code" placeholder="Search..." />
使用
<input type="text" name="postal_code" id="postal_code" placeholder="Search..." />
它应该可以正常工作。