首页 > 解决方案 > posting form data with ajax javascript and php

问题描述

I'm trying to post form data though a POST AJAX call in JavaScript for a chat system I'm creating, how come the following is not working? I tried to get some documentation but I cannot find it.

<div id="view-chat-form">
    <input id="message" type="text" name="chat_message" placeholder="write a message..."/>, 
    <input type="button" value="send" onclick="sendData()"/>
</div>

and using the followin AJAX code to send the request without loading the page with an hashed string to hide the chat id

<script type="text/javascript">
   function sendData(){
            var cm = document.getElementById("message").value;
            var xhttp = new XMLHttpRequest();
            xhttp.open("POST", "chat_form.php", true);
            xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
        }
</script>

and the followin php code to insert the message into the messages table

<?php
    include "session.php";
    include "connection.php";
    $id = "";
    $hashed_id = mysqli_real_escape_string($connection, $_POST["q"]);
    $sql = "SELECT * FROM chats WHERE SHA2(id, 512) = ?";
    $stmt = mysqli_prepare($connection, $sql);
    mysqli_stmt_bind_param($stmt, 's', $hashed_id);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $count = mysqli_num_rows($result);
    
    if($count > 0){
        $row = mysqli_fetch_assoc($result);
        $id = $row["id"];
    } else {
        mysqli_free_result($result);
        mysqli_close($connection);
        header("Location: chat_error.php");
    }
    
    $msg = mysqli_real_escape_string($connection, $_POST["chat_message"]);
    $username = $_SESSION["username"];
    $date = date("d/m/Y");
    $time = date("H:i:s");
    $sql = "INSERT INTO chat_messages(chat_id, username, message, date, time) VALUES(?, ?, ?, ?, ?)";
    $stmt = mysqli_prepare($connection, $sql);
    mysqli_stmt_bind_param($stmt, 'dssss', $id, $username, $msg, $date, $time);
    mysqli_stmt_execute($stmt);
?>

标签: javascriptphpajax

解决方案


做这样的事情

<script type="text/javascript">
function sendData(){
    var id = <?php echo $hashed_id; ?>;
    var msg = <?php echo $_POST['chat_message']; ?>;
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "chat_form.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(id,msg);
}
</script>

推荐阅读