AJAX将选定的日期('articleDate')发送到PHP文档,然后在SQL语句中使用它,但是,在运行PHP时,在代码中出现了未定义的错误我在哪里声明:
$date = $_POST['articleDate'];
表示该值未发布到PHP。 我已经检查了代码,它在语义上似乎运行良好。是否有单独的方法在AJAX中发布“日期”值?
在不使用AJAX的情况下,PHP代码可以使用,并且通过方法(带有“提交”按钮的提示)来发布表单。
HTML <body>
代码:
<div id="wrapper"> <!--wrapper start-->
<!--include navbar-->
<?php include 'include/navbar.php';?>
<div class="container" id="content"><!--container start-->
<div class="jumbotron"><!--jumbotron start-->
<div class="col-xs-12">
<div class="row" id="date">
<form>
<input class="form-control" type="date" id="articleDate" onchange="viewArticle(this.value)">
</form>
</div>
</div>
<div class="row">
<div id="article">
</div>
</div> <!--Row end-->
</div><!--Jumbotron End-->
<?php require 'include/footer.php';?>
</div> <!--container end-->
JavaScript
window.onload=function(){
document.getElementById("articleDate").value="";
}
function viewArticle()
{
$.ajax({
type: "POST",
url: "../pages/include/viewArticle.php",
data: {
Date: document.getElementById("articleDate").value
},
success: function (response) {
document.getElementById("article").innerHTML=response;
},
error: function(xhr, status, error) {
alert('article not sent');
},
});
}
PHP代码(错误所在的是日期初始化(未定义的变量):
#Get date
$date = $_POST['articleDate'];
$stmt = $conn->prepare("SELECT * FROM Article WHERE articleDate=? ORDER BY articleDate desc");
$stmt->bind_param("s", $date);
if($date !== "")
{
if($stmt->execute()){
$data = $stmt->get_result();
#Check number of rows statement selects
if($data->num_rows > 0)
{
#print data
while($row = $data->fetch_assoc()){
#create div
echo ' <div class="col-lg-4 col-md-6 col-sm-6 col-xs-12" id="articleDiv">';
echo "<img class='img-responsive' id='articleImage' src=".$row['articleThumbnail'].">";
echo '<h3><a href="article.php?id='.$row['articleId'].'">'.$row['articleHeadline'].'</a></h3>';
echo '<p>',$row['articleSummary']," ",'</p>';
echo '<div class="row" id="rowDetails">';
echo '<p>' , $row['articleDate']," | " , $row['articleTopic'],'</p>';
echo '</div>';
echo '</div>';
}
}
else
{
echo "<p>No articles exist on this date</p>";
}
}
#$stmt->close();
#$conn->close();
}
else{
echo "Date not working";
}
未定义变量 = $ date
答案 0 :(得分:4)
在PHP中,您将通过名称articleDate
获得发布的参数:
$_POST['articleDate']
当您发送Date
时。
您有两种选择:
您可以像这样在JS中更改参数名称:
data: {
articleDate: document.getElementById("articleDate").value
},
或者您可以在您的PHP代码中更改它,例如:
$_POST['Date']