首页 > 解决方案 > AJAX jQuery MySQL PHP问题插入数据库

问题描述

我正在尝试在不刷新的情况下向数据库添加评论。我设法让数据进入数据库,但不知何故我把它弄坏了。我已经遵循了几个教程,现在我想我在某个地方搞混了。这可能是一件小事。

我认为是 jQuery 搞砸了。

所以... MySQL 数据库很简单——comment_id、title、body

HTML

<form class="comment-form" action="php/addcomment.php" method="post">
                    <div class="form-group">
                        <h2>Add Comment</h2>
                        <label for="comment_title">Title</label>
                        <input type="text" id="comment_title" name="comment_title" class="form-control" value="">
                    </div><!--/formgroup-->
                    <div class="form-group">
                        <label for="comment_body">Body</label>
                        <textarea name="comment_body" id="comment_body" class="form-control" rows="8" cols="40"></textarea>
                    </div><!--/formgroup-->
                    <button type="button" class="btn btn-primary pull-right" id="comment-btn">Submit</button>
                </form><!--/form-->

添加评论.php

include('dbconnect.php');

$con = mysqli_connect($servername,$username,$password,$database);

$title = $_POST['comment_title'];
$body = $_POST['comment_body'];

$sql = "insert into comments (title, body) values ('$title','$body')";

if(mysqli_query($con, $sql)){
echo 'success';
}

jQuery AJAX

$(document).ready(function() {
        //option A
        $("#comment-form").submit(function(e){
            e.preventDefault(e);
        });
    });

    $('#comment-btn').click(function(){
     $.post( 
     $('#comment_form').attr('action'),
     $('#comment_form :input').serializeArray(),
     function(result){
         $('#result2').html(result);
        }
     );
    });

如果您想了解更多信息,请不要犹豫,任何帮助将不胜感激!数据库确实连接 btw 我不觉得我必须包含 dbconnect.php

谢谢!

表格(HTML)

标签: phpjquerymysqlajaxinsert

解决方案


推荐阅读