使用ajax发送表单

时间:2017-07-25 02:48:05

标签: javascript php ajax

我正试图用ajax来表达我的表格,但这不会做任何事情

这是我的表格

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

这是我的功能

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

这个是inser.php(我写得正确)

<?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);


?>

我不会这样,因为当我点击我的按钮时,我不想刷新我的页面,如果我从inser.php进入,当我提交时我得到这个错误

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

我该怎么做?我还有其他功能

这是我的完整脚本

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

答案版

我的网址中的

就像这样

  

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

id的id 4或x值是我“聊天”的正确功能所必需的,因为这是我如何接收消息

当我用@Rex Martinus的知情答案提交时

网址更改为

  

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

所以这会消除URL上的id并显示此错误

enter image description here

  

数据库

这是数据库显示的方式

enter image description here

在这一刻$id是4,无论是接收器还是发射器,在我的查询中搜索两者

并且$us是数字3,在查询中是相同的

  

在重新开始之前我有什么需要

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

有新答案

enter image description here

  

版本实际代码

的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 个答案:

答案 0 :(得分:1)

试试这个

<!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);
}
?>

请参阅此处Jquery .serialize()

答案 1 :(得分:0)

给你一个身份证,这样的事情应该有效

<form method="POST" id="my-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">

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

<script>
     $(function () {
            $('body').on('submit', '#my-form', function (e) {
                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;
            })
        })
</script>

答案 2 :(得分:0)

试试这个:

html:

<form onsubmit='return onSubmit(this)'>
</form>

js:

function onSubmit( form ){
     $.ajax({
                    type:'POST',
                    dataType: "json",
                    url:'inser.php',
                    data:{data : JSON.stringify( $(form).serializeArray() )},
                   success : function(data){
                     alert("Success");                 
                    }
                });

  return false; //don't submit
}

在你的php中:

 $formdata = json_decode($_POST['data'],true); // this contains your form data 

修改

抱歉,我忘记了form.serializearray()将返回json array名称值对

我为你的修复创建了一个小提琴:https://jsfiddle.net/9gg81m0e/

  

在那个小提琴中,我使用了&#34; json&#34;作为关键,以便jsfiddle将   了解您的案例请求只发送结果对象   并在表单输入名称作为键的另一端使用post方法   参数

您也可以随时使用浏览器控制台(f9)

在js代码中找到错误