Reputation: 123
AJAX is sending a selected date - ('articleDate') - to a PHP document where it is then used within an SQL statement, however, I am getting an undefined error in my code when I run the PHP, on the line where I declare:
$date = $_POST['articleDate'];
Meaning that the value is not being posted to PHP. I have checked the code and it seems to be working fine semantically. Is there a separate method for posting 'date' values within AJAX?
The PHP code works when there is no AJAX being used, and the form is being Posted via method - with the cue of a Submit Button.
HTML <body>
code:
<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 code (date initiation is where the error is(undefined variable):
#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";
}
Undefined varibale = $date
Upvotes: 3
Views: 62
Reputation: 67505
In the PHP you're getting the posted argument by name articleDate
:
$_POST['articleDate']
When you're sending Date
instead.
You've two choices :
You could change the argument name in your JS like :
data: {
articleDate: document.getElementById("articleDate").value
},
Or you could change it in your PHP code like :
$_POST['Date']
Upvotes: 4