卡在Ajax表单上以提交mysql [英] Stuck on Ajax Form to mysql submission

查看:50
本文介绍了卡在Ajax表单上以提交mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我擅长php和html,但是我仍在学习js.而且我坚持要创建一个表单,该表单将提交要插入到mysql中的表单数据,而无需加载page(ajax).

I am good in php and html, however my I am still learning js. And I am stuck on creating a form which will submit form data to be inserted in mysql without loading page(ajax).

以下是我的表格:

<form id="panel1" action="rep-submit.php" method="post">
                                 <div class="form-group">
                                    <input type="text" name="rep_author" id="rep_author" placeholder="Your Name" class="form-control">
                                 </div>
                                <div class="form-group">
                                    <input type="email" name="rep_email" id="rep_email" placeholder="Your Email" class="form-control">
                                 </div>
                                 <div class="form-group">
                                      <textarea class="form-control" id="rep_comment" name ="rep_comment"rows="3" placeholder="Your comment"></textarea>
                                </div>
                                    <input type="hidden" value="<?php echo $comment_id; ?>" id ="rep_to">
                                    <input type="hidden" value="<?php echo $postp_id; ?>" id ="rep_post_id">
                               <input id="repsub" type="button" class="btn btn-primary" value="Submit">
                               </form>

下面是我的post.js,我花了很多在线指南来制作这样的js代码:P,花了1天的时间仍无法正常工作.请帮助

Below is my post.js I took a lot of online guide to make such js codes :P, it took 1 day to complete still not working. Please help

$(document).ready(function(){
$("#repsub").on('click', function(event) {
event.preventDefault();
                            $("#repsub").attr("disabled", "disabled");
                            var rep_author = $('#rep_author').val();        
                            var rep_email = $('#rep_email').val();      
                            var rep_comment = $('#rep_comment').val();
                            var rep_to = $('#rep_to').val();
                            var rep_post_id = $('#rep_post_id').val();
                            var url = $("#panel1").attr("action");
                            alert(url);
                            $.ajax({
                                url: url, 
                                type: "POST",
                                data: {
                                rep_author: rep_author, 
                                rep_email: rep_email,
                                rep_comment: rep_comment,
                                rep_to: rep_to,
                                rep_post_id: rep_post_id
            },
            cache: false,   
            success: function(dataResult){
                var dataResult = JSON.parse(dataResult);    
                document.write(rep_comment);    

                if(dataResult.statusCode==200){
                        console.log("success");
                        $("#repsub").removeAttr("disabled");
                        $('#panel1').find('input:text').val('');
                        alert("success");
                        }
                        else if(dataResult.statusCode==201){                     
                        alert("Error occured !");                   
                        }
                        }

                            });
                            });
                            });

最后是rep-submit.php

Finally below is rep-submit.php

    <?php include_once("includes/connection.php");
if(isset($_POST['rep_submit']))
    {
        global $connection;
        connection();
        $author = $_POST['rep_author'];
        $email = $_POST['rep_email'];
        $comment = $_POST['rep_comment'];
        $rep_to = $_POST['rep_to'];
        $post_id = $_POST['rep_post_id'];
       $com_rep = "yes,".$rep_to;

        $query = "INSERT INTO comment(comment_post_id,comment_author,comment_email,comment_content,comment_reply) ";
        $query .= "VALUES('$post_id','$author','$email','$comment','$com_rep')";
        $result = mysqli_query($connection, $query);

        if(!$result)
            {
                echo "There is some issue posting your reply on that comment<br>";
                echo mysqli_error($connection);
                echo json_encode(array("statusCode"=>201)); 
        }   
            else
            {
                echo "reply sucessfully sent for approval";

        $query = "SELECT * FROM comment WHERE comment_id = '$rep_to'";
        $result = mysqli_query($connection, $query);
        $row = mysqli_fetch_assoc($result);
        $com_count = $row['comment_reply_count'];
        $new_count = $com_count + 1;
        $query = "UPDATE comment SET ";
        $query .= "comment_reply_count = '$new_count' ";
        $query .= "WHERE comment_id = '$rep_to'";
        $result = mysqli_query($connection, $query);
        echo json_encode(array("statusCode"=>200));
        }   


    }
?>

推荐答案

您的代码无法正常工作,因为您需要调用Javascript代码正在监听的click事件的preventDefault()方法.

Your code is not working as intended because you need to call the preventDefault() method of the click event your Javascript code is listening to.

您必须更改代码的这一部分:

You have to change this part of your code:

$("#repsub").on('click', function() {

对此:

$("#repsub").on('click', function(event) {
    event.preventDefault();

通过这种方式,可以防止提交按钮#repsub的默认行为,即提交#panel1表单.

In this way, you prevent the default behavior of your submit button #repsub, which is to submit the #panel1 form.

此外,还必须将rep_submit: 1添加到通过AJAX发送的数据对象中:

Also, you have to add rep_submit: 1 to the data object you send via AJAX:

data: {
    rep_author: rep_author, 
    rep_email: rep_email,
    rep_comment: rep_comment,
    rep_to: rep_to,
    rep_post_id: rep_post_id,
    rep_submit: 1 // Add this
},

大多数PHP代码未执行,因为AJAX请求中的rep_submit元素丢失:isset($_POST['rep_submit'])返回了false.

Most of your PHP code wasn't executed because the rep_submit element in the AJAX request was missing: isset($_POST['rep_submit']) returned false.

此外,HTML代码中存在一个重要错误:#repsub输入的类型为submit..您需要通过将点更改为submit来删除该点,以便正确显示表单提交按钮.

In addition, there is an important error in your HTML code: your #repsub input is of type submit.. You need to remove the dot by changing it to submit in order to correctly show a form submit button.

最后一个问题是,在PHP中,如果成功,则在回显最终的json编码数据之前先回显一些文本.您必须删除行echo "reply sucessfully sent for approval";.这样,您的JS代码将能够解析响应并显示成功"警报.

The last problem is that in the PHP, in case of success, you are echoing some text before echoing the final json-encoded data. You have to remove the line echo "reply sucessfully sent for approval";. This way, your JS code will be able to parse the response and show the "success" alert.

我认为,如果您处理表单的submit事件而不是提交输入的click事件,那会更好.为此,您只需以这种方式更改代码:

I think it would be better if you handle the submit event of your form instead of the click event of your submit input. To do this, you should simply change your code this way:

$("#panel1").on('submit', function(event) {
    event.preventDefault();


您不应使用document.write(),尤其是如果调用它的代码是异步的(它将覆盖所有页面内容).使用 Node.insertBefore() Node.appendChild()或JQuery的


You should't use document.write(), especially if the code which calls it is asynchronous (it will overwrite all the page content). Use Node.insertBefore(), Node.appendChild() or JQuery's append() and prepend() methods.

您应该以一致的方式从PHP输出数据.如果要使用JSON,请始终返回正确的JSON数据,并且不要将echo用于其他目的.在这种情况下,为简单起见,您可以在成功时输出以下数据:

You should be outputting data from your PHP in a consistent way. If you want to use JSON, then always return correct JSON data and don't use echo for other purposes. In this case, to keep it simple, you could output this data on success:

{
    "success": true
}

如果发生错误,请输出以下内容:

In case of error, output this:

{
    "success": false,
    "error_message": "Your error message"
}

通过这种方式,您将能够以一种简单,干净的方式处理服务器的响应.

In this way, you will be able to handle your server responses in a simple and clean way.

Dharman的评论是正确的:您需要防止SQL注入.您可以在此处找到一些很好的信息.

Dharman's comment is correct: you need to prevent SQL injection. You can find some good information on how to do it here.

有用的链接

这篇关于卡在Ajax表单上以提交mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆