So, bascially, I have made a page with posts, called entry.php which gets the $_GET[‘id’] as a post id that is situated in the database. Ultimately, it looks like, for instance:
/entry.php?id=css-clearfix-explained
And here’s the PHP code from my php file entry.php :
<?php require_once("../inc/config.php");
require_once(ROOT_PATH . "inc/entries.php");
require('../connection.php');
require('../session.php');
require('../user.php');
$user = new User();
$entry = $collection->findOne(array("_id" => $_GET['id']));
$action = (!empty($_POST['post-comment']))
&& (($_POST['post-comment']) === "Post a Comment") ? 'save_post' : 'show_form';
switch($action) {
case 'save_post':
try{
$connect = new MongoClient();
$choqlet = $connect->selectDB('choqlet');
$entries = $choqlet->selectCollection('entries');
$post_comment = array('$push' =>
array("comments" => array(
"_id" => new MongoId(),
"comment" => $_POST['comment'],
"author" => $user->username,
"date" => new MongoDate()
)
)
);
$entries->update(array(
"_id" => $_GET["_id"]), $post_comment);
header("Location: " . BASE_URL);
} catch(MongoConnectionException $e) {
die("Failed to connect to database" .
$e->getMessage());
}
catch(MongoException $e) {
die("Failed to insert data". $e->getMessage());
}
break;
case 'show_form':
default:
}
It is MongoDB database, but it doesn’t matter, its not the issue.
The issue is that on the entry.php page there is a button which, when clicked, pulls the AJAX request and displays the comment_form.php, which is here:
<?php
require('../connection.php');
require('../session.php');
require('../user.php');
$user = new User();
if (!isset($_SESSION['user_id'])) { ?>
<h4 class="small grey">You need to <a href="../login.php">log in</a> in order to post a message.</h4>
<?php } else { ?>
<form method="post">
<table class="table borderless">
<tr>
<td>
<textarea class="form-control" name="comment" rows="3" id="comment" placeholder="Post a Comment..."></textarea>
</td>
</tr>
</table>
<h4 class="small"> logged as <strong><a href="#"><?php echo $user->username; ?></strong></a></h4>
<input type="submit" id="post-comment" value="Post a Comment">
</form>
<?php } ?>
So, as seen, it checks whether the user is logged in, and if he/she is logged in, displays the form, otherwise, shows the log in direction.
The problem is with action=“” of that form, because when I post anything the entry.php doesn’t recognize that $_POST request, but is instead, recognized only within the comment_form.php boundary.
How to solve that issue? I’d prefer to leave it in this way, because it can be further animated, as it is by jQuery/AJAX way.