jb93
jb93

Reputation: 77

Adding comments into database with PHP (Using AJAX to prevent page reload)

I'm trying to make a comments system which adds to the database using PHP and AJAX without having to reload the page (if I reload the page it will pick another film suggestion at random).

At the moment it doesn't seem to work - when I click "Submit comment" it reloads the page (loading a different film) and nothing is inserted to the database.

I'd also like to be able to have the comment appear in the comments section below after submission if possible.

Thanks for your help

yourfilm.php (the process page that displays a film, specified by options selected on a form on the previous page)

<?php //recaptcha_process.php 
    require_once("php/checklog.php");
    require_once('php/functions.php'); 
    require_once('php/db_connect.php');

    include_once("php/home_start_logged.php");  

    if (!$db_server){ 
        die("Unable to connect to MySQL: " . mysqli_connect_error()); 
        $db_status = "not connected"; 
    }else{

        //CODE TO QUERY DATABASE TO GO HERE
        //Capture form data, if anything was submitted
        if (isset($_POST['genreList']) && ($_POST['genreList'] != '')){
            $genre = clean_string($db_server, $_POST['genreList']);
            //create the SQL query
            $query = "SELECT * FROM films WHERE genreID=$genre ";

            //$endquery = " AND (";
            $endquery = "";
            $orFlag = false;

            if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){                   
                $endquery .= " netflix IS NOT NULL";
                $orFlag = true;
            }
            if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
                if($orFlag){
                    $endquery .= " OR ";
                }
                $endquery .= " lovefilmInstant IS NOT NULL";
                $orFlag = true;
            }
            if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
                if($orFlag){
                    $endquery .= " OR ";
                }
                $endquery .= " blinkbox IS NOT NULL";
            }               
            if($endquery != "") $query .= " AND (" . $endquery . ")";

            $query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;"; 


            //query the database
            mysqli_select_db($db_server, $db_database);
            $result = mysqli_query($db_server, $query);
            if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);

            //if there are any rows, print out the contents
            if ($row = mysqli_fetch_array($result)) {

                //Whether to display links or not for purchase and streaming
                if ($row['netflix'] == null){
                    $netflixLink = "";
                }else{
                    $netflixLink = "<a href='" . $row['netflix'] . "'>" . "<img class='streamingLogo' src='images/netflix_logo.jpg' alt='Watch on Netflix'></a>";
                }
                if ($row['lovefilmInstant'] == null){
                    $lovefilmLink = "";
                }else{
                    $lovefilmLink = "<a href='" . $row['lovefilmInstant'] . "'>" . "<img class='streamingLogo' src='images/Lovefilm_logo.jpg' alt='Watch on LoveFilm'></a>";
                }
                if ($row['blinkbox'] == null){
                    $blinkboxLink = "";
                }else{
                    $blinkboxLink = "<a href='" . $row['blinkbox'] . "'>" . "<img class='streamingLogo' src='images/blinkbox_logo.jpg' alt='Watch on Blinkbox'></a>";
                }
                if ($row['itunes'] == null){
                    $iTunesLink = "";
                }else{
                    $iTunesLink = "<a href='" . $row['itunes'] . "'>" . "<img class='streamingLogo' src='images/itunes_logo.jpg' alt='Buy now on iTunes'></a>";
                }
                if ($row['googlePlay'] == null){
                    $googleplayLink = "";
                }else{
                    $googleplayLink = "<a href='" . $row['googlePlay'] . "'>" . "<img class='streamingLogo' src='images/googleplay_logo.jpg' alt='Buy now on Google Play'></a>";
                }               
                if ($row['amazon'] == null){
                    $amazonLink = "";
                }else{
                    $amazonLink = "<a href='" . $row['amazon'] . "'>" . "<img class='streamingLogo' src='images/amazon_logo.jpg' alt='Buy now on Amazon'></a>";
                }


                //Body content for film             
                $str_result = "<section>
                                <div class='sectionColumnThird'>
                                    <img class='poster' src='images/posters/" . $row['poster'] . ".jpg'>
                                </div>
                                <div class='sectionColumnTwoThirds'>
                                    <h2>" . $row['filmName'] . "</h2>
                                    <p class='filmDate'>(" . $row['filmYear'] . ")</p>
                                    <a class='formButton' href='#comments'>Jump to comments</a>
                                </div>
                               </section>
                               <section>
                                   <h3>Not interested?</h3>
                                   <a class='formButton' href='#yourfilm.php'>Find another film</a>
                               </section>
                               <section>
                                <h3>Rating</h3>
                                <p><span class='bold'>IMDB:</span> " . $row['ratingIMDB'] . "</p>
                                <p><span class='bold'>Rotten Tomatoes:</span> " . $row['ratingRottenTomatoes'] . "</p>
                                <p><span class='bold'>Metacritic:</span> " .  $row['ratingMetacritic'] . "</p>
                               </section>
                               <section>
                                <h3>Synopsis</h3>
                                <p>" . $row['synopsis'] . "</p>
                               </section>
                               <section>
                                <h3>Trailer</h3>
                                <div class='videoWrapper'>
                                    <iframe src='//www.youtube.com/embed/" . $row['trailer'] . " ' frameborder='0' allowfullscreen></iframe>
                                </div>
                               </section>
                               <section>
                                <h3>Cast & Crew</h3>
                                <p><span class='bold'>Director:</span> " . $row['director'] . "</p>
                                <p><span class='bold'>Writers:</span> " . $row['writer'] . "</p>
                                <p><span class='bold'>Cast:</span> " . $row['cast'] . "</p>
                               </section>
                               <section>
                                <h3>Details</h3>
                                <p><span class='bold'>Certificate:</span> " . $row['certificate'] . "</p>
                                <p><span class='bold'>Country:</span> " . $row['country'] . "</p>
                                <p><span class='bold'>Language:</span> " . $row['language'] . "</p>
                               </section>
                               <section>
                                <h3>Streaming Services</h3>"
                                . $netflixLink . $lovefilmLink . $blinkboxLink ."
                               </section>
                               <section>
                                <h3>Buy now</h3>"
                                . $iTunesLink . $googleplayLink . $amazonLink ."
                               </section>
                               <section>
                                <form id='frmFilmComments' action='yourfilm.php' method='post'>
                                    <a id='comments' class='anchor'></a><h3>Comments</h3>
                                    <p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
                                    <select class='selectbox' name='yesornoList'>
                                        <option value='Yes'>Yes</option>
                                        <option value='No'>No</option>
                                    </select>

                                    <p id='commentResult'></p>
                                    <p><span class='bold'>Provide your feedback here:</span></p>
                                    <textarea id='commentBox' class='insertComment' rows='2' cols='30' name='comment'></textarea><br>
                                    <input class='formButton' type='submit' id='submitComment' name='submitComment' value='Submit comment' /> 
                                </form>";

                $filmID=$row['filmID'];

                mysqli_free_result($result);



                //Print out Like it - Comments              
                $likeitQuery = "SELECT * FROM comments
                                JOIN users on users.userID = comments.userID
                                WHERE likeit='Yes' AND filmID=$filmID"; 
                $likeitResult = mysqli_query($db_server, $likeitQuery); 
                if (!$likeitResult) die("Database access failed: " . mysqli_error($db_server)); 
                while($row = mysqli_fetch_array($likeitResult)){ 
                    $str_likedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
                                          . $row['comment'] . "<br>
                                          &#x25B2;(" . $row['upvotes'] . ") ǀ &#x25BC; (" . $row['downvotes'] . ")</p>"; 
                } 
                mysqli_free_result($likeitResult);
                $likedcomments = "<div class='half subSection'>
                                    <h4>Liked it</h4>"
                                    . $str_likedcomments . 
                                 "</div>";



                //Print out disike it - Comments
                $dislikeitQuery = "SELECT * FROM comments
                                JOIN users on users.userID = comments.userID
                                WHERE likeit='No' AND filmID=$filmID"; 
                $dislikeitResult = mysqli_query($db_server, $dislikeitQuery); 
                if (!$dislikeitResult) die("Database access failed: " . mysqli_error($db_server)); 
                while($row = mysqli_fetch_array($dislikeitResult)){ 
                $str_dislikedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
                                      . $row['comment'] . "<br>
                                      &#x25B2;(" . $row['upvotes'] . ") ǀ &#x25BC; (" . $row['downvotes'] . ")</p>";  
                } 
                mysqli_free_result($dislikeitResult);
                $dislikedcomments = "<div class='half subSection'>
                                    <h4>Disliked it</h4>"
                                    . $str_dislikedcomments . 
                                 "</div>";


            }else{
                $str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='home.php'>Please try again.</a></p></section>";
            }


        }else{
            $str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";

        }

    $message = $str_result . $likedcomments . $dislikedcomments . "<section/>";

    }

    //Comments
    $userID = $_SESSION['userID'];
    $likeit = $_POST['yesornoList'];
    $comment = clean_string($db_server, $_POST['commentBox']);

    //Get any submitted comments and insert 

     if ($comment != '') { 
         $query = "INSERT INTO comments (userID, filmID, comment, likeit) VALUES ($userID, $filmID, $comment)"; 
         mysqli_select_db($db_server, $db_database); 
         mysqli_query($db_server, $query) or 
                        die("Insert failed: " . mysqli_error($db_server)); 
         $message = "Thanks for your comment!"; 
     } 

    require_once('php/db_close.php');

?>


            <div id="top" class="content container headerMargin">
                <div class="content wrapper">    
                   <?php echo $message; ?>
                </div>
            </div>

<?php 
require_once('php/home_end.php');
?>

addCommentAJAX.js

$("#submitComment").click( function() {
 $.post( $("#frmFilmComments").attr("action"), 
         $("#frmFilmComments :input").serializeArray(), 
         function(info){ $("#commentResult").html(info); 
   });
 clearInput();
});

$("#frmFilmComments").submit( function() {
  return false; 
});

function clearInput() {
    $("#frmFilmComments :input").each( function() {
       $(this).val('');
    });
}

home_start_logged.php is simply a header template, I won't post it all but it contains:

<script src="js/addCommentAJAX.js" type="text/javascript"></script>

EDIT: Added more specific info about the error (see above).

Upvotes: 1

Views: 617

Answers (3)

Momin
Momin

Reputation: 868

can you change this

$("#submitComment").click( function() {
 $.post( $("#frmFilmComments").attr("action"), 
         $("#frmFilmComments :input").serializeArray(), 
         function(info){ $("#commentResult").html(info); 
   });
 clearInput();
});

to

function onclicksth() {
 $.post( $("#frmFilmComments").attr("action"), 
         $("#frmFilmComments :input").serializeArray(), 
         function(info){ $("#commentResult").html(info); 
   });
 clearInput();
}

and change submitComment type to button? There is a better way to do this too:

   //rough code including the submit and post data
 $('form.frmFilmComments').on('submit', function() {
                        if(confirm('Do u want to input that field')){
                        fields-=1;
                        var obj = $(this), 
                            url = obj.attr('action'),
                            method = obj.attr('method'),
                            data = {};
                        $("#hdnlstcount").val(fields);
                        //console.log(fields);
                        obj.find('[name]').each(function(index, value) {

                            var obj = $(this),
                                name = obj.attr('name'),
                                value = obj.val();
                            data[name] = value;
                        });
                        $.ajax({
                            url: url,
                            type: method,
                            data: data,
                            success: function(response2) {
                                //do sth with success response
                            }
                        });
                        return false; //disable refresh
                                             clearInput();
                        }
                    });

Upvotes: 0

zerzer
zerzer

Reputation: 602

there is not enough data to make an exact solution, but i see two problems :

1 - you are not preventing the default form submit in your submit function event.preventDefautlt() or just change the input type attribut in your form to button rather than submit

2 - if you wan't the comment that the user just sent to show up then you can use the function append() to make it show at the end of the comment section this is the fastest way to do this rather than waiting for it to show from the database

Upvotes: 1

Jordan
Jordan

Reputation: 1433

So what is probably happening here is that you haven't used event.preventDefault() This will stop your submit button from reloading the page, which will allow your ajax code and your code posting the comment to finally get run.

http://api.jquery.com/event.preventdefault/

The idea behind preventDefault is that it stops the submit button from doing its default behavior, which is submitting a form and reloading the page.

Upvotes: 0

Related Questions