user3843098
user3843098

Reputation:

Submitting form data with javascript (No page reload)

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.

Upvotes: 2

Views: 504

Answers (4)

rink.attendant.6
rink.attendant.6

Reputation: 46218

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.

Upvotes: 2

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

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

Upvotes: 1

Yalamber
Yalamber

Reputation: 7580

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/

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174967

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.

Upvotes: 1

Related Questions