Monday 3 September 2018

PHP Ajax does not return anything

I have a commenting system so when the submit button is pressed It sends the comment to the database and then adds it to the comments list on the page.

comments.php
    <div id="comments" itemscope itemtype="http://schema.org/UserComments">
                              <?php do { ?>
            <div class="comment shadow effect">
                    <p class="left tip" title="<?php echo $row_getComments['comment_author'];?> Said">
                     <img class="avatar" src="<?php echo $row_getComments['avatarurl'];?>" /></p>
                          <p class="body right" itemprop="creator"><?php echo $row_getComments['comment_entry'];?></p>

                    <div class="details small">
                        <span class="blue"><?php echo timeBetween($row_getComments['communt_date'],time());?></span> · <a class="red" href="#" onclick="$(this).delete_comment(<?php echo $row_getComments['comment_id'];?>); return false;">Remove</a>
                    </div>
                </div>
                            <?php } while ($row_getComments = mysql_fetch_assoc($getComments)); ?>
                            </div>

    //Add Comment//
                            <div class="add_comment">
            <div class="write shadow comment">
                <p class="left">
                    <img class="avatar" src="#" />
                </p>

                <form method="POST" name="addcomment">
<p class="textarea right"><input type="hidden" name="username" value="<?php echo $_SESSION['username'];?>" />
                    <textarea class="left" cols="40" rows="5" name="post_entry"></textarea>
        <input class="left" value="SEND" type="submit" />
                   </p> </form>

            </div>
            <a onclick="$(this).add_comment(<?php echo $row_getSinglePost['post_id'];?>);return false;" class="right effect shadow" href="#">Add Comment</a>
        </div>

ajax.js- this is how it sends and recieves information. I know the submit button works because it grays it out
 jQuery.fn.add_comment = function (page_id) {
var that = $(this);

that.hide(10, function () {
    that.prev().show();
});

that.parent().find('input[type=submit]').click(function () {
    var value = $(this).prev().val();
    if (value.length < 3) {
        $(this).prev().addClass('error');
        return false;
    } else {
        var input = $(this);
        input.prev().attr('disabled', true);
        input.attr('disabled', true);
        $.post("ajax.php", {
            post_id: page_id,
            comment: value
        }, function (data) {
            if (data.error) {
                alert("Your Comment Can Not Be Posted");
            } else {
                that.parent().prev('.comments').append('<div class="comment rounded5"><p class="left"><img class="avatar" src="' + data.avatar + '" /></p><p class="body right small">' + data.comment + '<br /><div class="details small"><span class="blue">' + data.time + '</span> · <a class="red" href="#" onclick="$(this).delete_comment(' + data.id + '); return false;">Remove</a></div></p></div>');
                input.prev().val('');
            }
            input.prev().attr('disabled', false);
            input.attr('disabled', false);
        },'json');

    }
    return false;
});

};
ajax.php
require_once('connections/Main.php');
$username = $_SESSION['username'];
mysql_select_db($database_Main);
function getavatar($username){
    $result = mysql_query("SELECT profile_pic FROM `users` WHERE `username` = '$username' LIMIT 1");
    $row = mysql_fetch_row($result);
    return $row[0];
}
    if(isset($_POST['post_id']) and isset($_POST['comment'])){
        $post_id = intval($_POST['post_id']);
        $comment = mysql_escape_string($_POST['comment']);
        $time = time();
        $insertcom = mysql_query("INSERT INTO `blog_comments` (`author`, `post_num`, `comment_entry`, `communt_date`) VALUES ($username, '{$post_id}', '{$comment}', '{$time}')");
        if($insertcom){
            $id = mysql_insert_id();
            exit(json_encode(array(
                'id' => $id,
                'avatar' => getavatar($username),
                'time' => timeBetween($time, time()),
                'comment' => $comment,
            )));
        }
    }

Also how would I error check this to submit an error if say the query didn't work?

  1. Use echo instead of exit like Rafael said. But you don't need to use die() or exit() or whatever. Clean code don't need to use die() or exit().
  2. You used a comma behind $comment inside your array, but no entry follows the comma (in my code the 'error' => false follows.
  3. You can check if the insert was a success when you ask if the mysql_affected_rows was greater than zero (http://www.php.net/manual/en/function.mysql-affected-rows.php). mysql_affected_rows returns the rows that were affected by INSERT, UPDATE and DELETE.
Code:
if($insertcom){
    //Check if INSERT was successfully
    if(mysql_affected_rows() > 0) {
        $id = mysql_insert_id();
        echo(json_encode(array(
            'id' => $id,
            'avatar' => getavatar($username),
            'time' => timeBetween($time, time()),
            'comment' => $comment, //here is the ,
            //Added line to state if error
            'error' => false
        )));
    } else {
        //Echo to return error when INSERT was unsuccessful
        echo(json_encode(array('error' => true)));
    }
}

0 comments:

Post a Comment