send form with 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);
}
?>

Upvotes: 0

Views: 230

Answers (3)

Rex Martinus
Rex Martinus

Reputation: 155

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

Upvotes: 1

Arun pandian M
Arun pandian M

Reputation: 882

try this :

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
}

in your php :

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

EDIT

sorry my mistake i forget that form.serializearray() will return json array with name value pair

i created a fiddle for your fix : https://jsfiddle.net/9gg81m0e/

In that fiddle i used "json" as key so that the jsfiddle will understand the request for your case just send only the result object and use post method on the other end with form input name as a key parameter

also you can always find the error in js code with browser console (f9)

Upvotes: 0

Kevin P
Kevin P

Reputation: 601

Give you form an id, something like this should work

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

Upvotes: 0

Related Questions