scubbastevie
scubbastevie

Reputation: 37

PHP Adding a comment box to a rating system

UPDATE - Have added in code to javascript to handle the comment insert as advised in the first answer, but unfortunately nothing is inserting for the comment, can anyone advise why the comment is not being submitted to my database?

I am a novice at coding, firstly I know I am using mysql fucntions in my code and they are deprecated in future versions of PHP, I'm running 5.5. I have a few days to get my current code working with this desired functionality which is a throw away prototype, so for now I'm stuck with them. I would really appreciate no comments about these functions but rather positive feedback if possible on my actual question :)

I have created a rating system which is working as intended, i want to add a comment box so users can comment on my videos also. I have added the following code to the bottom of my index file.

<div id="addCommentContainer">
    <p>Please leave a comment on what you thought of the tutorial</p>
    <form id="addCommentForm" method="post" action="" >
        <div>
            <textarea name="body" id="body" cols="60" rows="5"></textarea>
        <br>
            <input type="submit" id="submit" value="Submit" />

I have obviously added variables and a column in my database to receive the comments. However, my ratings submit but my comments inserts nothing into my database. Could this be due to the posts for my ratings and comments conflicting?

Can anyone advise how to merge these POSTS to insert together? I have enclosed both my index and ajax files.

Index.php

<?php  
    session_start();
    include_once 'dbconnect.php';

    if( !isset( $_SESSION['user'] ) ) header("Location: index.php");

    $res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
    $userRow=mysql_fetch_array( $res );

        $post_id = 1; 
    ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-20" />
<title>Welcome - <?php echo $userRow['username']; ?></title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
 <div id="left">
    <label>NHSCT eNISAT Tutorials</label>
    </div>
    <div id="right">
     <div id="content">
         Welcome <?php echo $userRow['forename']; ?>&nbsp;<a href="eNISATVids.php?home">Return to Tutorials page</a>&nbsp;&nbsp;<a href="logout.php?logout">Sign Out</a>
        </div>
    </div>
    <br>
    <br>
    <br>
    <br>
    <br>
<p align="center"><img src="title.jpeg" width="400" height="100" alt="title.jpeg">
<br>
  <link rel="stylesheet" href="style.css" type="text/css" />
        <link type="text/css" rel="stylesheet" href="css/example.css">


    <div class="tuto-cnt">

        <div class="rate-ex1-cnt">
            <div id="1" class="rate-btn-1 rate-btn"></div>
            <div id="2" class="rate-btn-2 rate-btn"></div>
            <div id="3" class="rate-btn-3 rate-btn"></div>
            <div id="4" class="rate-btn-4 rate-btn"></div>
            <div id="5" class="rate-btn-5 rate-btn"></div>
        </div>

        <hr>

        <div class="box-result-cnt">
            <?php
                $query = mysql_query("SELECT * FROM enisat1_rate"); 
                while($data = mysql_fetch_assoc($query)){
                    $rate_db[] = $data;
                    $sum_rates[] = $data['rate'];
                }
                if(@count($rate_db)){
                    $rate_times = count($rate_db);
                    $sum_rates = array_sum($sum_rates);
                    $rate_value = $sum_rates/$rate_times;
                    $rate_bg = (($rate_value)/5)*100;
                }else{
                    $rate_times = 0;
                    $rate_value = 0;
                    $rate_bg = 0;
                }
            ?>
            <hr>
            <h3>This tutorial has been rated <strong><?php echo $rate_times; ?></strong> times.</h3>
            <hr>
            <h3>The average rating is <strong><?php echo $rate_value; ?></strong> stars.</h3>
            <hr>
            <div class="rate-result-cnt">
                <div class="rate-bg" style="width:<?php echo $rate_bg; ?>%"></div>
                <div class="rate-stars"></div>
            </div>
            <hr>
            <center>
    <div id="addCommentContainer">
    <p>Leave a comment on what you thought of the tutorial</p>
    <br>
    <form id="addCommentForm" method="post" action="eNISATVids.php" >
        <div>
            <textarea name="comments" id="comments" cols="50" rows="5"></textarea>
        <br>
            <input type="submit" id="submitcomment" value="Submit" />
    </form>
        </div><!-- /rate-result-cnt -->

    </div><!-- /tuto-cnt -->

    <script>

     $( document ).ready(function() {

        // rating script
        $(function(){ 
            $('.rate-btn').hover(function(){
                $('.rate-btn').removeClass('rate-btn-hover');
                var therate = $(this).attr('id');
                for (var i = therate; i >= 0; i--) {
                    $('.rate-btn-'+i).addClass('rate-btn-hover');
                };
            });

            $('.rate-btn').click(function(){    
                var therate = $(this).attr('id');
                var dataRate = 'submit=rate&post_id=<?php echo $post_id; ?>&rate='+therate; //
                $('.rate-btn').removeClass('rate-btn-active');
                for (var i = therate; i >= 0; i--) {
                    $('.rate-btn-'+i).addClass('rate-btn-active');
                };

                $.ajax({
                    type : "POST",
                    url : "http://localhost/Tna/E1ajax.php",
                    data: dataRate,
                    success:function(){}
                });

            });
        });

        // javascript for handling your comment:
$("#submitcomment").click(function() {
     var comments = $("#comments").val();
     $.ajax({
        url: "http://localhost/Tna/E1ajax.php",
        type: "POST",
        data: { "comments": comments },
        success: function(back)
            {
            alert(back);
            }
        });
});
});  

    </script>

</body>
</html> 

Ajax.php

<?php

session_start();
include_once 'dbconnect.php';

if(!isset($_SESSION['user']))
{
 header("Location: index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);

    if($_POST['submit'] == 'rate'){
        //search if the userID has already gave a note
        $userID=$_SESSION['user'];
        $therate = $_POST['rate'];
        $thepost = $_POST['post_id'];
        $comments = $_POST['comments'];

        $query = mysql_query("SELECT * FROM enisat1_rate where user_id= '$userID'"); 
        while($data = mysql_fetch_assoc($query)){
            $rate_db[] = $data;
        }

        if(@count($rate_db) == 0 ){
            mysql_query("INSERT INTO enisat1_rate (id_post, user_id, rate, comments )VALUES('$thepost', '$userID', '$therate', '$comments')");
        }else{
            mysql_query("UPDATE enisat1_rate SET rate= '$therate' WHERE user_id = '$userID'");
        }
    } 
?>

Thank You

Upvotes: 0

Views: 1924

Answers (1)

Malvolio
Malvolio

Reputation: 376

Some hints: - Your textarea element for the comment has the id "body" and does not seem to get handled at all in the Javascript part. - Your form element for the comment part does not seem to have a closing tag. - You could have a better overview on your code if you placed your javascript below your html.

update: Hi @scubbastevie, you could get the contents of your textarea element e.g. like this:

var comment = $("#body").val();

and construct an $.ajax call passing this comment variable to your php to store it to the database.

update: Hi @scubbastevie, I recommend a scheme like this, this is simplified:

<!-- your markup for rating -->
....

<!-- markup for comment: ->
<input type = "textarea" id = "comment" />
<input type = "submit" id = "submitcomment" value = "comment" />

<script>
$( document ).ready(function() {

// javascript for handling your rating

// javascript for handling your comment:
$("#submitcomment").click(function() {
     var comment = $("#comment").val();
     $.ajax({
        url: "yourajax.php",
        type: "post",
        data: { "comment": comment },
        success: function(back)
            {
            alert(back);
            }
        });
});

</script>

I recommend you to complete the courses for javascript and jquery at codecademy, they are very useful und fun.

Upvotes: 1

Related Questions