Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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);
?>
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Don't understand why you are using php $_POST in javascript, it will not work. Try using document.getElementById() to grab the chat message.

The correct way is shown below.

<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>

Also in your PHP code, why using json_decode()? The post is not in JSON format. Correct that also.

Change below code

$data = json_decode(file_get_contents("php://input"));
$hashed_id = $data->q;
$msg = $data->chat_message;

to

$hashed_id = $_POST["q"];
$msg = $_POST["chat_message"];
about 4 years ago · Juan Pablo Isaza Denunciar

0

Do something like this

<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>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda