0

I'm having an issue getting a form to submit and display the comment without the page refreshing (in-place) but when I click on the button, it takes me to the top of the page but does not perform any actions, does not insert into the database and thus does not display the comments in the page.

It is supposed to place the comment in the appropriate place with a fade effect.

Credits and Demo for the script: Original Script Here

The script provided int he link above, works if I try it as it comes but I had to modify it to fit my needs and this is what I have.

The Form:

<div class="comment-form">
    <form id="form" action="" method="post">
        <div class="top-form">
            <span class="parent name">
                <input class="field" type="hidden" name="Name" value="<?php echo $_SESSION["UserName"]; ?>" />
                <input class="field" type="text" name="Name" value="<?php echo $_SESSION["UserName"]; ?>" disabled="disabled">
            </span>
            <span class="parent name">
                <input class="field" type="hidden" name="ID" value="<?php echo $_SESSION["UserID"]; ?>" />
                <input class="field" type="text" name="ID" value="<?php echo $_SESSION["UserID"]; ?>" disabled="disabled"> 
            </span>
            <span class="parent last">
                <input class="field" type="hidden" name="PageID" value="<?php echo $_GET['PageID']; ?>" />
                <input class="field" type="text" name="PageID" value="<?php echo $_GET['PageID']; ?>" disabled="disabled">  
            </span>
            <div class="clear"></div>
        </div>
        <div class="bottom-form">
        <label>Choose an Option</label>
        <select id="commentbox" name="comment" class="bs-select form-control">
            <option disabled selected value> -- Options -- </option>
            <option value="First Option">First Option</option>
            <option value="Second Option">Second Option</option>
            <option value="Third Option">Third Option</option>
        </select>
        <button class="btn btn-icon submit" name="btn-sumbit" type="submit" id="submit" value="Post Message"><span class="icon"></span>Post Message</button>
        </div>
    </form>
</div>

<div class="comments">
    <div class="section-title">
        <h3>Messages</h3>
    </div>
    <ul class="level-1">
    <div class="comment-block">
    <?php echo $postedcomments; ?> <!-- loads previous comments on page load. it works. -->
    </div>
    </ul>
</div>

The script

located in the same page as the form.

<script>
$(document).ready(function(){
  var form = $('form');
  var submit = $('#submit');

  form.on('btn-submit', function(e) {
    // prevent default action
    e.preventDefault();
    // send ajax request
    $.ajax({
      url: 'data/queries/comment-insert.php',
      type: 'POST',
      cache: false,
      data: form.serialize(), //form serialized data
      beforeSend: function(){
        // change submit button value text and disabled it
        submit.val('Posting...').attr('disabled', 'disabled');
      },
      success: function(data){
        // Append with fadeIn see http://stackoverflow.com/a/978731
        var item = $(data).hide().fadeIn(800);
        $('.comment-block').append(item);

        // reset form and button
        form.trigger('reset');
        submit.val('Post Message').removeAttr('disabled');
      },
      error: function(e){
        alert(e);
      }
    });
  });
});
</script>

The Query

comment-insert.php

<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include_once 'include/dbconfig.php';
include_once 'include/dbconnection.php';
$conn = dbconnect();

if (!empty($_POST['comment'])) {
        $Name = mysqli_real_escape_string($conn, $_POST['Name']);
        $PageID = mysqli_real_escape_string($conn, $_POST['PageID']);
        $ID = mysqli_real_escape_string($conn, $_POST['ID']);
        $Comment = mysqli_real_escape_string($conn, $_POST['comment']);

        $sql = "INSERT INTO comments
        (PageID, PosterID, PosterName, PostDate, Comment)
        VALUES
        ('$PageID', '$ID', '$Name', now(), '$Comment')";

        mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));    
}
?>

<li><span class='comment'>
<span class='picture'>
<span><img src='users/images/<?php echo $_SESSION['Image'] ?>'></span>
</span>
<span class='content'><span class='title'><b><?php echo $Name ?></b>, Said:</span><br><?php echo $Comment ?></span>
<span class='clear'></span>
</span>
</li>

<?php
    mysqli_close($conn);
endif?>
BlueSun3k1
  • 757
  • 5
  • 21
  • 39
  • Anything in the developer console? Any thing in PHP error log? – chris85 May 05 '16 at 20:46
  • name="btn-sumbit" doesn't match your jQuery event handler (form.on('btn-submit', function(e)) -> sumbit <> submit – Webomatik May 05 '16 at 20:47
  • Also, your jQuery event handler should refer to either a class or an id, like form.on('.submit') or form.on('#submit') – Webomatik May 05 '16 at 20:48
  • @chris85 , nothing in the developer console. no JS errors. Nothing in the php_error.log. – BlueSun3k1 May 05 '16 at 20:54
  • form.on('btn-submit') doesn't execute! 'btn-submit' is the name if the submit button, but it doesn't refer to any jQuery object. – Webomatik May 05 '16 at 20:56
  • @Webomatik, I corrected the name="btn-sumbit" to btn-submit, tried it and still the same result. I tried using the button id submit as .submit and also as #submit but still the same. just goes to the top of the page when I click on the button and does not trigger the query. Here's a link to the demo so you can see what it's supposed to do. http://demo.w3bees.com/jquery-ajax-comment-system/ – BlueSun3k1 May 05 '16 at 21:01

2 Answers2

2

This works:

$(document).ready(function() {
    //var form = $('#form');
    //var submit = $('#submit');

    $('#submit').on('click', function(e) {
        e.preventDefault(); 
        // the rest of your code goes here
    })
});
Webomatik
  • 844
  • 7
  • 7
  • form.on('btn-submit') : btn-submit is not an event (click, submit, etc.) – Webomatik May 05 '16 at 21:19
  • Tried it. Now I get the following error. TypeError: form.serialize is not a function. data: form.serialize(), //form serialized data – BlueSun3k1 May 05 '16 at 22:23
  • I decided to update jquery to the latest version (1.12.3) and now I get no js errors with your modified version and now php_error log is throwing an error. PHP Warning: include_once(): Failed opening 'include/dbconnection.php'. This is odd because the form document is outside the include folder and it should be able to call it. I don't have that error if I just run a form without using ajax to submit it. only get that error when using ajax. – BlueSun3k1 May 05 '16 at 22:58
  • 1
    Ok, different problem altogether! Try using absolute path, like include_once '/var/www/project1/include/dbconfig.php'; – Webomatik May 05 '16 at 23:01
  • well it's starting to work one piece at a time. I noticed your suggestion and decided to do it this way instead and now it works but still have one more error not related to this one but back to the original post. this saves me the trouble if I move the project to another folder. $ds = DIRECTORY_SEPARATOR; $base_dir = realpath(dirname(__FILE__) . $ds . '..') . $ds; include_once("{$base_dir}..{$ds}include{$ds}dbconfig.php"); include_once("{$base_dir}..{$ds}include{$ds}dbconnection.php"); – BlueSun3k1 May 05 '16 at 23:27
  • the other error is with the html content that is supposed to "fadein" when the data is inserted into the database. should I open a new question for that or is it ok to continue on here? – BlueSun3k1 May 05 '16 at 23:29
  • Yes please, it's better to open a new one ; ) – Webomatik May 05 '16 at 23:30
0

Your jQuery event handler refers to an non-existent jQuery object. Try replacing the first line of the event handler with this:

form.on('submit', function(e) {
Webomatik
  • 844
  • 7
  • 7
  • I followed your instructions and now I got a js error in the developer console. I changed var submit = $('#submit'); to var submit = $('btn-submit'); and form.on('btn-submit, function(e) { to form.on('submit, function(e) { as you suggested. Now when I click on the button, nothing happens at all and the console says TypeError: i is undefined and points to the jquery-1.9.1.min.js line 6 – BlueSun3k1 May 05 '16 at 22:15
  • var submit = $('btn-submit') is no good. See the other answer above, it works ; ) – Webomatik May 05 '16 at 22:22