javascript - AJAX 验证改进

标签 javascript php jquery ajax

所以我有一段 AJAX 可以正常工作,但我想为其添加一些验证。我不希望它发送空信息。AJAX 是为评论系统完成的。它从表单,然后使用 php 将其插入数据库。我遇到的问题是它只是将空注释插入数据库

index.php

<?php 
    require_once("menu.php");
?>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script  src="comments.js" type="text/javascript" ></script>
        <script type="text/javascript">
            function validateForm()
            {
                var comment = document.getElementsByName('comment').value;

                if (comment == "" ) 
                {
                    alert("Please fill in all the fields");
                    return false;
                }
                else
                {
                    return true;
                }
            }
        </script>
<?php

    $connection = connectToMySQL();


    $selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";

    $result = mysqli_query($connection,$selectPostQuery)
        or die("Error in the query: ". mysqli_error($connection));
    while ($row = mysqli_fetch_assoc($result)) 
    {
        $postid = $row['ID'];

?>
        <div class="wrapper">
        <div class="titlecontainer">
        <h1><?php echo $row['Title']?></h1>
        </div>
        <div class="textcontainer">
        <?php echo $row['Content']?>
        </div>
<?php
        if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
        {
?>
            <div class="imagecontainer">
            <img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
            </div>
<?php
        }
?>
        <div class="timestampcontainer">
        <b>Date posted :</b><?php echo $row['TimeStamp']?>
        <b>Author :</b> Admin
        </div>
<?php
        #Selecting comments corresponding to the post
        $selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";

        $commentResult = mysqli_query($connection,$selectCommentQuery)
            or die ("Error in the query: ". mysqli_error($connection));

        #renderinf the comments

        echo '<div class="comment-block_' . $postid .'">';

        while ($commentRow = mysqli_fetch_assoc($commentResult)) 
        {
?>
            <div class="commentcontainer">
            <div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
            <div class="commentcontent"><?php echo $commentRow['Content']?></div>
            <div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
            </div>
<?php
        }
?>
        </div>
<?php 

        if (!empty($_SESSION['userID']) ) 
        {
?>
            <form method="POST" class="post-frm" action="index.php" onsubmit="return validateForm();">
            <label>New Comment</label>
            <textarea name="comment" class="comment"> </textarea>
            <input type="hidden" name="postid" value="<?php echo $postid ?>">
            <input type="submit" name ="submit" class="submitComment"/>
            </form>
<?php
        }
        echo "</div>";
        echo "<br /> <br /><br />"; 
    }
 require_once("footer.php") ?>

我的 AJAX 代码。我尝试过进行一些验证,但它无法正常工作,而且我不知道它出了什么问题。我对 AJAX 很陌生,所以无法自己调试它。

 $(document).ready(function(){

   $(document).on('click','.submitComment',function(e) {

        e.preventDefault();
        //send ajax request
        var form = $(this).closest('form');
        var comment = $('.comment');
        if (!comment.val()){
                alert('You need to write a comment!');       
        }
        else{
            $.ajax({
                url: 'ajax_comment.php',
                type: 'POST',
                cache: false,
                dataType: 'json',
                data: $(form).serialize(), //form serialize data
                beforeSend: function(){
                    //Changeing submit button value text and disableing it
                    $(this).val('Submiting ....').attr('disabled', 'disabled');
                },
                success: function(data)
                {
                    var item = $(data.html).hide().fadeIn(800);
                    $('.comment-block_' + data.id).append(item);

                    // reset form and button
                    $(form).trigger('reset');
                    $(this).val('Submit').removeAttr('disabled');
                },
                error: function(e)
                {
                    alert(e);
                }
            });
        }
    });
});

我要插入数据库的 php 代码。

 <?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):

    session_start();
    include('connection.php');
    $connection = connectToMySQL();

        $userId = $_SESSION['userID'];
        $username = $_SESSION['username'];
        $postId = $_POST['postid'];
        $comment = $_POST['comment'];
        $date_format = " Y-m-d  g : i : s";
        $time = date ($date_format);


          $insertCommentQuery = "INSERT INTO `tblcomments` 
                                 (`Content`,`UserID`,`PostID`,`Timestamp`) 
                                VALUES (
                                   '$comment','$userId','$postId',
                                    CURRENT_TIMESTAMP)";
          $result = mysqli_query($connection,$insertCommentQuery);

$obj = array();

$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
                    <div class="commentusername"><h1> Username :'.$username.'</h1></div>
                    <div class="commentcontent">'.$comment.'</div>
                    <div class="commenttimestamp">'.$time.'</div>
               </div>';
echo json_encode($obj);

    connectToMySQL(0);
   endif?>

最佳答案

你永远不会调用函数validateForm()

还有这部分

if (!comment.val()){
                alert('You need to write a comment!');       
        }
如果存在带有类 comment 的输入字段,

将始终通过,即使它是空的。你可以这样做:

//send ajax request
if(validateForm()===false){
    alert('You need to write a comment!');
    return false;
    }
    else{
     ....

关于javascript - AJAX 验证改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23977501/

相关文章:

javascript - 如何根据元素的位置设置准确的背景位置?

javascript - 从 XSLT 调用函数错误 : Namespace does not contain any functions

javascript - Three.js 凹凸贴图未更新

php - 当 csv 表标题与 mySQL 表标题不匹配时使用 LOAD DATA INFILE 语句?

php - HTML 表单 + PHP、页面重定向

javascript - Jquery 位置没有给出预期的结果

javascript - 在javascript中将对象传递给html中的函数?

php - 批量通过电子邮件发送 mysql 表设置?

javascript - 修改伪元素:after's width using javascript

javascript - jQuery UI 对话框未第二次打开,但背景无法访问