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.

  • 4
    You need to use AJAX in regards with your problem – John Robertson Aug 19 '14 at 07:01
  • You can use AJAX to avoid page refreshing.. – Jenz Aug 19 '14 at 07:01
  • There's a good example about making Ajax calls with jQuery at the question [Submit form without page reloading](http://stackoverflow.com/questions/2866063/submit-form-without-page-reloading?rq=1) – ljacqu Aug 19 '14 at 07: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=""` – Kevin Aug 19 '14 at 07:05
  • possible duplicate of [JavaScript post request like a form submit](http://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit) – Nateowami Aug 19 '14 at 07:07

4 Answers4

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.

rink.attendant.6
  • 36,468
  • 57
  • 89
  • 143
  • 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 –  Aug 19 '14 at 13:20
  • In that case you can use a class selector instead of ID on the form. – rink.attendant.6 Aug 19 '14 at 13:21
  • I'm really new to javascript, could you edit your answer to show me how please? –  Aug 19 '14 at 13:26
  • 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 –  Aug 19 '14 at 13:55
  • Does this form exist on page load or is it being dynamically generated after the page has been loaded? – rink.attendant.6 Aug 19 '14 at 13:59
  • It should be, I edited my question to show the whole area where it loads in. –  Aug 19 '14 at 14:05
  • Are you including the jQuery library (usually called `jquery.min.js`) in your head of your page? Do you see any console errors? – rink.attendant.6 Aug 19 '14 at 15:03
  • I have the version that comes with bootstrap –  Aug 19 '14 at 15:11
  • I've made another edit but if this still does not work then there is something else that is wrong and there does not exist sufficient information to diagnose the problem. – rink.attendant.6 Aug 20 '14 at 00:38
  • Okay, now let me ask, will this just go in a –  Aug 20 '14 at 02:04
  • Ah, the script works now but is not submitting the info... I can try one more thing –  Aug 20 '14 at 02:06
  • Hmm, nope, now it is not submitting the data... it's as if the POST is not being submitted now. –  Aug 20 '14 at 02:20
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.
Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292
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/

Yalamber
  • 6,783
  • 13
  • 57
  • 80
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

Utkarsh Dixit
  • 3,476
  • 2
  • 12
  • 34