无法使用AJAX识别HTML表单元素的值

时间:2017-10-21 10:56:08

标签: javascript php jquery html ajax

我正在尝试使用AJAX在我的项目中实现一个消息系统,但是我遇到了一些问题,因为我是AJAX的新手。 下面的代码能够完美地将MsgMain.php文件中的输入数据发送到MsgInsert.php。但是,当我尝试从$_POST['msgSend'] MsgMain.phpMsgInsert.php时,它失败了。

AJAX代码在MsgMain.php上

$(document).ready(function(){
    $("#chatBtn").click(function(){
        $("#msgBtn").val("chat");
    });
    $("#pmBtn").click(function(){
        $("#msgBtn").val("pm");
    });
});
$(function() {
    $("#msgBtn").click(function() {
        var textcontent = $("#msgInput").val();
        var dataString = 'content='+ textcontent;
        if(textcontent=='')
        {
            alert("Enter some text..");
            $("#msgInput").focus();
        }
        else
        {
            $.ajax({
                type: "POST",
                url: "msg/MsgInsert.php",
                data: dataString,
                cache: true,
                success: function(response){
                    document.getElementById('content').value='';
                    $("#msgBtn").focus();
                }
            });
        }
        return false;
    });
});
仅适用于HTML表单的

MsgMain.php文件代码

<form action="MsgInsert.php" id="frmBox" name="msgSend" method="POST" onsubmit="return formSubmit();">
    <div class="input-group ">
        <input type="text" class="form-control" name="msgBox" id="msgInput" title="Enter your message" required>
        <div class="input-group-btn">
            <button class="btn btn-success w3-hover-white w3-hover-text-green" type="submit" id="msgBtn" title="Send your message" value="chat"><i class="glyphicon glyphicon-send"></i></button>
        </div>

    </div>
</form>

MsgInsert.php文件代码,当我删除$_POST['msgSend']

的if语句时效果很好
    <?php
if(!isset($_SESSION['login_user'])){
    header("location: ../index.php"); // Redirecting To Home Page
}
if (isset($_POST['content'])) {
    if (isset($_POST['msgSend'])) {
        $conn = mysqli_connect("localhost", "root", "", "msg");
        if (!$conn) {
            die('Could not connect: ' . mysqli_error($conn));
        }
        $content=$_POST['content'];
        mysqli_query($conn, "INSERT INTO `msgpm`(`id`, `msgFrom`, `msgTo`, `msg`) VALUES ('','bob','ram','$content')");
    }
}
?>

很抱歉,如果已经提出过这类问题。

2 个答案:

答案 0 :(得分:0)

根据JS中的这一行,您没有发送msgSent属性:

var dataString = 'content='+ textcontent;

我只能通过content看到您可以使用的$_POST['content']

试试这个:

var dataString = 'content='+ textcontent + '&msgSent' + '<?php echo $_POST['msgSent']; ?>';

答案 1 :(得分:0)

您必须根据msgSend的实施方式传递MsgInsert.php参数,如下所示:

$("#msgBtn").click(function () {
    var textcontent = $("#msgInput").val();

    if (textcontent == '') {
        alert("Enter some text..");
        $("#msgInput").focus();
    }
    else {
        var dataString = 'content=' + textcontent + '&msgSend=1';
        $.ajax({...});
    }
});

在将用户生成的内容保存到数据库中以避免sql注入时,请始终通过escaping来考虑prepared statements您的内容!