Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This tutorial’s core flow is: capture a post, like, unlike, or comment in the browser; send the action to a PHP endpoint with jQuery; update a MongoDB document; then refresh the stream’s HTML. Ashish Trivedi’s SitePoint part 2, published in 2013 and updated November 11, 2024, builds that beginner-oriented example on the data model and page flow introduced in part 1. Its sample uses procedural PHP and returns HTML fragments; treat it as a learning pattern, not production-ready social software.

How the page, PHP endpoints, and MongoDB fit together

The browser renders a stream of posts. Each post is associated with a user, and its markup exposes controls for liking or unliking and adding a comment. jQuery event handlers read the relevant form values and post ID, send them to a PHP endpoint, then update the page from the HTML returned by that endpoint.

The flow has four parts: a user action in the page, an AJAX request, a server-side check and MongoDB operation, and a DOM update. Part 1 establishes the users and posts collections, stream rendering, DOM IDs, and page-to-AJAX-to-PHP flow; read part 1 for that foundation. Part 2 applies the pattern to creating posts, likes, unlikes, and comments.

Represent users, posts, likes, and comments

Users and posts

The users collection stores a user’s _id, name, and profile_pic. A post references its author by ID rather than duplicating those display details. The application can look up the author’s name and profile-picture field when it renders the stream.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A post document contains these fields:

  • _id: the post’s MongoDB ID.
  • post_author_id: the author’s user ID.
  • post_text: the post content.
  • timestamp: when it was created.
  • total_likes and likes_user_ids: the displayed count and IDs of users who liked it.
  • comments and total_comments: embedded comment records and their displayed count.

Embedded activity has trade-offs

Keeping comments and liker IDs inside the post document makes the tutorial’s updates and rendering straightforward: one post is the unit being changed. It also means the arrays grow as activity accumulates. A production system should choose deliberately between embedded activity and separate collections, based on expected volume, access patterns, and the need to query or moderate activity independently. The tutorial does not establish a production scale threshold for that choice.

Create a post and prepend it to the stream

  1. Read and validate the text in the browser. The Create New Post button calls new_post with the session user ID. JavaScript reads #post_textarea and uses $.trim to reject empty or whitespace-only input.
  2. Send the request. jQuery $.post sends user_id and post_text to insert_new_post.php.
  3. Build and insert the document. PHP creates a MongoId, derives a timestamp, checks that the request user matches the session user, and inserts the post into posts_collection. The initial values are total_likes: 0, an empty likes_user_ids array, an empty comments array, and total_comments: 0, alongside the author ID, text, and timestamp.
  4. Update the page. The success callback prepends the returned post markup to the stream, animates the first post, and clears the textarea.

The endpoint returns an HTML fragment, so the server is responsible for producing markup the existing page can insert. The tutorial notes that a real application would generally return JSON and render the response through a prepared template instead.

Like and unlike a post

Each post’s Like or Unlike control includes its post ID in its DOM ID. The post_like_unlike handler reads the current label and chooses post_like.php or post_unlike.php. The response callback changes the visible label and like count.

Action MongoDB changes in the example Browser result
Like $push adds the user ID to likes_user_ids; $inc increases total_likes by 1. Change the control label and visible count.
Unlike $pull removes the user ID from likes_user_ids; $inc decreases total_likes by 1. Change the control label and visible count.

The two endpoint operations are the tutorial’s basic demonstration, not a complete correctness strategy. A robust implementation must prevent duplicate likes and ensure an unlike cannot reduce the count below the number of remaining liker IDs. It should make the membership change and counter update consistent, including when requests arrive close together. The example does not provide a race-handling design.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add a comment to a post

The browser sends comment text and the post ID to new_comment.php. PHP pushes a subdocument into the post’s comments array with comment_id, comment_user_id, and comment_text, and increments total_comments by 1. The response contains rendered comment markup, which the client appends to the existing comment list.

As with likes, the displayed counter is stored separately from the array. If other code can edit or remove comments, it must keep total_comments in sync with the actual comments. The tutorial covers insertion, not a full edit, deletion, or moderation lifecycle.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What to strengthen before using this pattern in production

Trivedi presents procedural code as a beginner-friendly starting point and explicitly leaves security, design, richer social features, and operational concerns outside the tutorial’s scope. Before adapting it for a real application, address at least these issues:

  • Authorization: derive the acting user from the authenticated session on the server. Do not trust a client-supplied user_id as proof of identity; check that the user may act on the requested post.
  • Input validation: enforce content type and length limits, validate post and comment IDs, and reject malformed requests on the server. Browser-side trimming improves the interaction but is not server-side validation.
  • Output escaping: escape user-authored post and comment text when rendering HTML to prevent injected markup or script from becoming executable.
  • Idempotency and concurrency: make repeated likes, unlikes, and submissions safe; update membership and counts consistently if requests overlap or are retried.
  • Error handling: return clear failure responses for invalid input, missing posts, authorization failures, and database errors. Do not update the visible count as if a failed operation succeeded.
  • Maintainability: separate request handling, database operations, validation, and rendering. Prefer JSON responses and prepared templates when that fits the application; add a JavaScript or PHP framework only where its structure is useful.

The tutorial’s own closing invitation is to extend the example: “Implement object oriented code, use a JavaScript framework, use a PHP framework for the entire back end – the sky is the limit.” That is an invitation to build on a teaching example, not a claim that the sample already supplies those production safeguards.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.