douchuanghan1344 2017-07-25 02:48
浏览 43
已采纳

使用ajax发送表单

I'm trying to sen my form with ajax but this doens't do anything

this is my form

<form method="POST" onsubmit="return enviar();">
        <textarea name="message" id="message" placeholder="Enter message"></textarea>
        <input type="hidden" id="nombre" name="nombre" placeholder="Name" value="<?php echo $_SESSION['usuario']['nombre']?>">
        <input type="submit" name="submit" value="Send it">

        <input type="hidden" id="myId" name="idReceiver" value="<?php echo $id ?>">
        <input type="hidden" id="idEmitter" name="idEmitter" value="<?php echo $us ?>">
    </form>

and this is my function

function enviar(){
            var mensaje = document.getElementById('message').value;
            var nombre = document.getElementById('nombre').value;
            var idEmitter = document.getElementById('myId').value;
            var idReceiver = document.getElementById('idEmitter').value;

            var dataen = 'message='+mensaje +'&nombre='+nombre +'&myId='+idEmitter +'&idEmitter='+idReceiver;

            $.ajax({
                type:'POST',
                dataType: "html",
                url:'inser.php',
                data:dataen
            });
            return false;
        }

and this one is inser.php (i wrote correct)

<?php 

include 'db.php';
include '../functions.php';

var_dump($_POST);

    $name = $_POST['nombre'];
    $message = $_POST['message'];
    $emitter = $_POST['idEmitter'];
    $receiver = $_POST['idReceiver'];

    $query = "INSERT INTO messages (nombre, message, idEmitter, idReceiver, seenUsuario) VALUES ('$name', '$message', '$emitter', '$receiver', '0')";

    $run = $conexion->query($query);


?>

i wont this because i don't want to refresh my page when i make click on my button, if i get inside from inser.php when i make submit i get this errors

array(0) { }
Notice: Undefined index: nombre in C:\xampp\htdocs\talvez empresa\chat\inser.php on line 8

Notice: Undefined index: message in C:\xampp\htdocs\talvez empresa\chat\inser.php on line 9

Notice: Undefined index: idEmitter in C:\xampp\htdocs\talvez empresa\chat\inser.php on line 10

Notice: Undefined index: idReceiver in C:\xampp\htdocs\talvez empresa\chat\inser.php on line 11

how can i make this? i have another functions

this is my complete script

<script>
        function enviar(){
            var mensaje = document.getElementById('message').value;
            var nombre = document.getElementById('nombre').value;
            var idEmitter = document.getElementById('myId').value;
            var idReceiver = document.getElementById('idEmitter').value;

            var dataen = 'message='+mensaje +'&nombre='+nombre +'&myId='+idEmitter +'&idEmitter='+idReceiver;

            $.ajax({
                type:'POST',
                dataType: "html",
                url:'inser.php',
                data:dataen
            });
            return false;
        }

        function getPage(url, from, to) {
            var cached=sessionStorage[url];
            if(!from){from="body";} // default to grabbing body tag
            if(to && to.split){to=document.querySelector(to);} // a string TO turns into an element
            if(!to){to=document.querySelector(from);} // default re-using the source elm as the target elm
            if(cached){return to.innerHTML=cached;} // cache responses for instant re-use re-use

            var XHRt = new XMLHttpRequest; // new ajax
            XHRt.responseType='document';  // ajax2 context and onload() event
            XHRt.onload= function() { sessionStorage[url]=to.innerHTML= XHRt.response.querySelector(from).innerHTML;};
            XHRt.open("GET", url, true);
            XHRt.send();
            return XHRt;
        }

        window.onload(function() {
            setInterval(function(){
            var myId = document.getElementById("myId");
            var url = 'chat.php?id='+myId;
            getPage(url, "body", "chat");
            }, 1000);
        })
    </script>

EDITION OF ANSWER

in my URL is like this

http://localhost/talvez%20empresa/chat/index.php?id=4

the id 4 or x value of id, is required to the correct function of my "chat" because of this is how i can take the messages

when i make a submit with the knew answer of @Rex Martinus

the URL change to these

http://localhost/talvez%20empresa/chat/index.php?message=asd&nombre=Demon+Tech+System&submit=Send+it&idReceiver=4&idEmitter=3

so this disappear the id on the URL and show this erros

enter image description here

DataBase

this is how the DB shows

enter image description here

in these moment $id is the 4 it doesn't matter if is the receiver or the Emitter, in my query search for both

and the $us is the number 3, is the same in the query

WHAT I HAD BEFORE TO REFRESH

function ajax(){
            var req = new XMLHttpRequest();
            req.onreadystatechange = function(){
                if (req.readyState == 4 && req.status == 200) {
                    document.getElementById('chat').innerHTML = req.responseText;
                }
            }

            var myId = document.getElementById('myId');
            var url = 'chat.php?id='+myId;

            req.open('POST', url, true);
            req.send();

        }

        setInterval(function(){
            ajax()
        }, 1000);

WITH NEW ANSWER

enter image description here

Edition actual code

index.php

    <?php session_start();

include 'db.php';
include '../functions.php';

$emit = obtener_mensajes($conexion, $us);
$id=$_GET['id'];
var_dump($id);

comprobarSession();

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="assets/style.css">
    <link rel="stylesheet" href="assets/functions.js">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.js"></script>
</head>
<body>

<div id="container">
    <div id="chat_box">
        <div id="chat"><?php require_once 'chat.php'; ?></div>
    </div>
    <form id="form">
        <textarea name="message" id="message" placeholder="Enter message"></textarea>
        <input type="hidden" id="nombre" name="nombre" placeholder="Name" value="<?php echo $_SESSION['usuario']['nombre']?>">
        <input type="submit" name="submit" value="Send it" id="submit">

        <input type="hidden" id="myId" name="idReceiver" value="<?php echo $id ?>">
        <input type="hidden" id="idEmitter" name="idEmitter" value="<?php echo $us ?>">
    </form>

</div>

</body>
</html>

functions.js

function getPage(url, from, to) {
    var cached=sessionStorage[url];
    if(!from){from="body";} // default to grabbing body tag
    if(to && to.split){to=document.querySelector(to);} // a string TO turns into an element
    if(!to){to=document.querySelector(from);} // default re-using the source elm as the target elm
    if(cached){return to.innerHTML=cached;} // cache responses for instant re-use re-use

    var XHRt = new XMLHttpRequest; // new ajax
    XHRt.responseType='document';  // ajax2 context and onload() event
    XHRt.onload= function() { sessionStorage[url]=to.innerHTML= XHRt.response.querySelector(from).innerHTML;};
    XHRt.open("GET", url, true);
    XHRt.send();
    return XHRt;
}

$(document).ready(function(){
    $(document).on('click','#submit',function(e){
            e.preventDefault();
            var dataen = $("#form").serialize() + "&action";// the action here is for if(isset($_POST['action'])){do this}

            $.ajax({
                type:'POST',
                url:'inser.php',
                data:dataen
            });
    });
});

$(document).ready(function(){
    $(document).on('click','#submit',function(e){
            e.preventDefault();
            var dataen = $("#form").serialize() + "&action";// the action here is for if(isset($_POST['action'])){do this}

            $.ajax({
                type:'POST',
                url:'inser.php',
                data:dataen
            });
    });
});

chat.php

<?php

$id=$_GET['id'];

$sql = "SELECT ue.nombre de, ur.nombre a, c.message FROM  messages c
        INNER JOIN usuarios ue ON c.idEmitter = ue.idUsuario
        INNER JOIN usuarios ur ON c.idReceiver = ur.idUsuario
        WHERE (c.idEmitter = $id AND c.idReceiver = $us)
        OR (c.idEmitter = $us AND c.idReceiver = $id)
        ORDER BY sent ASC";

$stmt = $conexion->prepare($sql);
$stmt->execute();
$arrDatos = $stmt->fetchAll(PDO::FETCH_ASSOC);
imprimir($arrDatos);

//Una función para mostrar los datos
function imprimir($arrDatos)
{
    if ($arrDatos)
    {
        /**
         *  Construímos los datos  de forma limpia
        */
        $strHtml='CHAT:<br>';    
        foreach ($arrDatos as $row)
        {
            $strHtml.='<span style="color: green;>'.$row["a"].': </span>'.'<br>'.$row["message"].'<br>';
            $strHtml.='<span style="color: green;>'.$row["de"].': </span>'.'<br>'.$row["message"].'<br>';
        }
        echo $strHtml;
    }
}
?>

inser.php

<?php 

include 'db.php';
include '../functions.php';

if (isset($_POST['action'])) {

$name = $_POST['nombre'];
$message = $_POST['message'];
$emitter = $_POST['idEmitter'];
$receiver = $_POST['idReceiver'];
echo "name:".$name." message:".$message." emitter:".$emitter." receiver:".$receiver;


$query = "INSERT INTO messages (nombre, message, idEmitter, idReceiver, seenUsuario) VALUES ('$name', '$message', '$emitter', '$receiver', '0')";

$run = $conexion->query($query);
}
?>
  • 写回答

3条回答 默认 最新

  • dtvhqlc57127 2017-07-25 03:21
    关注

    try this

    <!DOCTYPE html>
    <html>
    <head>
        <title>test</title>
        <script type="text/javascript" src="jquery-3.2.1.js"></script>
    </head>
    <body>
    <div id="chat"><!-- Where the chat shows --></div>
    <form id="form">
        <textarea name="message" id="message" placeholder="Enter message"></textarea>
        <input type="hidden" id="nombre" name="nombre" placeholder="Name" value="usuario nombre">
        <input type="submit" name="submit" value="Send it" id="submit">
    
        <input type="hidden" id="myId" name="idReceiver" value="1">
        <input type="hidden" id="idEmitter" name="idEmitter" value="2">
    </form>
    
    <script type="text/javascript">
    $(document).ready(function(){
        ajaxcall();
        $(document).on('click','#submit',function(e){
                e.preventDefault();
                var dataen = $("#form").serialize() + "&action";// the action here is for if(isset($_POST['action'])){do this}
    
                $.ajax({
                    type:'POST',
                    url:'inser.php',
                    data:dataen,
                    success:function(response){
                        if (response == "") {}
                        alert(response);
                        ajaxcall();
                    }
                });
        });
    });
        // Calls read.php file
        function ajaxcall(){
    
        var myId = document.getElementById('myId').value;// the $us
        $.ajax({
            url: 'chat.php?id='+myId,// url where you will get the data
            success: function(data) {//  means if success do this
                    $('#chat').html(data);// id of the element that the data will be shown
                }
            });
        }
    </script>
    </body>
    </html>
    

    inser.php

    <?php 
    
    include 'db.php';
    include '../functions.php';
    
    if (isset($_POST['action'])) {
    
    $name = $_POST['nombre'];
    $message = $_POST['message'];
    $emitter = $_POST['idEmitter'];
    $receiver = $_POST['idReceiver'];
    echo "name:".$name." message:".$message." emitter:".$emitter." receiver:".$receiver;
    
    
    $query = "INSERT INTO messages (nombre, message, idEmitter, idReceiver, seenUsuario) VALUES ('$name', '$message', '$emitter', '$receiver', '0')";
    
    $run = $conexion->query($query);
    }
    ?>
    

    See here Jquery .serialize()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。