2

I've got a wall/social system (much like facebook) where there's statuses, but I want to be able to like, dislike and comment on a status without the page reloading, with the form below how could I complete this?

if(empty($_GET['action'])){

        postupdate();
        if(isset($_POST['sComment'])){
        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        $comment = mysqli_real_escape_string($dbc, trim($_POST['comment']));
        $sid = mysqli_real_escape_string($dbc, trim($_POST['sID']));
        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        $query = "INSERT INTO comments (`user`, `post`, `time`, `content`) VALUES ('".$_SESSION['user_id']."', '$sid', NOW(), '$comment')";
        $data = mysqli_query($dbc, $query);
        }
        $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        $query = "SELECT posts.*, user.*  FROM posts JOIN user ON user.user_id = posts.user_id JOIN friends ON friends.user = ".$userinfo['id']." AND friends.with = posts.user_id ORDER BY posts.post_id DESC";
        $data = mysqli_query($dbc, $query);
        while($row = mysqli_fetch_array($data)){
            echo'<div class="shadowbar">
                    <div class="postedBy"><b> Posted by <a href="index.php?action=user&u='.$row['user_id'].'" class="btn-link">'. $row['firstname'] .' '. $row['lastname'] .'</a> On '. date('M j Y g:i A', strtotime($row['postdate'])) .'</b></div>';
                    $parsed = $parser->parse($row['post']);
                echo '<pre>'.$parsed.'</pre>
                <hr>
                <form method="post" action="index.php" class="commentForm">
                    <fieldset>
                        <div class="input-group">
                            <textarea cols="150" rows="1" style="resize: none;" placeholder="Comment..." class="form-control" type="text" id="commentBox" name="comment"></textarea>
                        </div>
                        <input type="hidden" value="'.$row['post_id'].'" name="sID">
                    </fieldset>
                    <input class="Link LButton" type="submit" value="Add comment" name="sComment" />
                </form>             
            </div>';
            }
            echo '</div>';
            }

the form can be changed to fit the code. I'm assuming it's JavaScript that I will need to use.

5
  • 4
    You need to use AJAX in regards with your problem Commented Aug 19, 2014 at 7:01
  • You can use AJAX to avoid page refreshing.. Commented Aug 19, 2014 at 7:01
  • There's a good example about making Ajax calls with jQuery at the question Submit form without page reloading Commented Aug 19, 2014 at 7:03
  • this is broad you have a lot of ways to go since a big chunk of codes are not present. sidenote: value="$statusID", maybe you mean value="<?php echo $statusID; ?>" Commented Aug 19, 2014 at 7:05
  • possible duplicate of JavaScript post request like a form submit Commented Aug 19, 2014 at 7:07

4 Answers 4

2

Here's some code to get you started.

First of all, add an ID or class in order to easily identify the form(s):

<form method="post" action="index.php?action=comment" class='commentForm'>

Since you tagged jQuery, I shall use that:

$(document).on('submit', '.commentForm', function(e) {
    e.preventDefault(); // Prevents the default page reload after form submission

    $.ajax({
        type: $(this).prop('method'),
        url: $(this).prop('action'),
        data: $(this).serialize()
    }).done(function() {
        // Do something after it submits
        alert('Thanks for the comment!');
    }).fail(function() {
        // There was an error
        alert('An error occurred');
    });
});

You can read more about jQuery.ajax in the jQuery documentation.

Sign up to request clarification or add additional context in comments.

12 Comments

If I have multiple posts on the page will this still work? Say theres 6 posts in a row and I wanted to comment on one would it only comment on that one
In that case you can use a class selector instead of ID on the form.
I'm really new to javascript, could you edit your answer to show me how please?
This still reload the page... say I'm half way down the page an I comment, the page is still reloaded, however I also don't see the 'Thanks for the comment' alert
Does this form exist on page load or is it being dynamically generated after the page has been loaded?
|
1

Yes, you'll need to use JavaScript to send a POST request to the server. There are several jQuery plugins, but none of them are perfectly fit to your needs, so I recommend that you write your own.

The workflow should be like this:

  1. Initiate an XMLHttpRequest object
  2. Set the target equal to the form's action= attribute (extra points if you can get this information from the DOM without typing it manually again)
  3. Grab the data you want to submit from the form (again, using DOM)
  4. Send a POST request with the data you got from the form, to the target page.
  5. Target page should return a response of some sort, to tell the client that the submission went smoothly
  6. Client reads that response and displays a success message to the user.

Comments

1

Here is something that should be useful for you.

http://www.9lessons.info/2009/11/facebook-style-application-with-jquery.html

In short you need to use ajax to post request to your form's action url. you can use jQuery for that. http://api.jquery.com/jquery.ajax/

Comments

1

Use ajax to send and receive data. Use the code below

    <form method="post" action="index.php?action=comment" id="Form">
                <fieldset>
                    <legend>Status Update</legend>
                    <div class="input-group">
                        <textarea cols="150" rows="5" style="resize: none;" placeholder="Comment..." class="form-control" type="text" id="text" name="comment"></textarea>
                    </div>
                    <input type="hidden" id="hidden" value="$statusID" name="sID">
                </fieldset>
                <input class="Link LButton" type="submit" value="Add comment" name="submit" />
            </form><div class="container"></div>
        <script>
        $(document).ready(function(){
        $('#Form').submit(function(e) { 
         e.preventDefault(); // This will prevent the form to be submitted
        var hidden=$("#hidden").val();
        var comment=$("#text").val();
       $.post(
            "index.php", {
            comment: comment,
   sID:hidden
        },
         function (data) {
            $('#check').html(data);

        });
            });
        </script>

Your PHP file should look like this

<?php
$comment=$_REQUEST['comment'];
$sID=$_REQUEST['sID'];
echo $comment."<Br>".$sID;
?>

Hope this helps you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.