Send post to the same page without reloading [closed]

2

You can send a post to the same php page and then I can put if isset $_POST ['data'] do something? Because what I want is that when I click, an element is added to my php array that I save in the session but I do not want to see the effect of the page loading

    
asked by Gabriel Rodriguez 14.08.2018 в 16:43
source

2 answers

1

Before I start I have to tell you that it is a bad idea to store a large amount of data in the session variables. They tend to slow down the execution of each of the scripts that use session_start() and, in addition, increases memory usage.

Once that point is clarified, what you need is to send the data to the server through XMLHttpRequest (more known as XHR or AJAX ) . This sending does not cause the refresh of the page and allows you to modify your content by javascript according to the response obtained.

The jQuery function library will make your job much easier through jQuery.ajax() :

$.ajax({
  url: 'https://tu_pagina_web.es/tu_script.php',
  method: 'post',
  data: datos,
}).done(function( datos ) {
  console.log(datos);
);

In the example that I put below, I used the property data so that the data is available in $_POST['data'] as you requested in the question:

<?php
/* Iniciamos el uso de las variables de sesión */
session_start();
/* Comprobamos si el campo "data" ha sido recibido por POST */
if (isset($_POST['data'])) {
    /* Agregamos los datos recibidos a la variable de sesión */
    array_push($_SESSION['datos'], $_POST['data']);
    header('Content-type: application/json; charset=utf-8');
    die(json_encode(true));
}

As you can see I have sent an HTTP header called Content-type with the value application/json; charset=utf-8 so that the value returned by the PHP is interpreted as a native javascript data.

In proof of concept, I have also created a second request GET to refresh the content of the session variable on the web page without needing to refresh its content.

Here is the complete proof-of-concept code:

<?php
/* Iniciamos el uso de las variables de sesión */
session_start();
/* Si aún no existe la clave de sesión requerida la creamos con una matriz vacía */
if (!isset($_SESSION['datos'])) {
    $_SESSION['datos'] = [];
}
/* Comprobamos si el campo "data" ha sido recibido por POST */
if (isset($_POST['data'])) {
    /* Agregamos los datos recibidos a la variable de sesión */
    array_push($_SESSION['datos'], $_POST['data']);
    header('Content-type: application/json; charset=utf-8');
    die(json_encode(true));
}
/* Comprobamos si el campo "actualizar" ha sido recibido por GET */
if (isset($_GET['actualizar'])) {
    /* Entregamos los datos codificados en JSON */
    header('Content-type: application/json; charset=utf-8');
    die(json_encode($_SESSION['datos'], JSON_PRETTY_PRINT));
}
?><!DOCTYPE html>
<html lang="es">

<head>
    <title>Título de ejemplo</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
</head>

<body>
    <h3>Formulario:</h3>
    <p><input type="text" id="texto" placeholder="Introduzca un texto aquí" size="50" />
    <button id="boton">Actualizar datos</button></p>
    <h3>Resultado del envío:</h3>
    <pre id="resultado">-</pre>
    <h3>Contenido de <code>$_SESSION['datos']</code>:</h3>
    <pre id="datos"><?= htmlspecialchars(json_encode($_SESSION['datos'], JSON_PRETTY_PRINT)) ?></pre>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script>
        /* Cuando pulsemos en el botón enviaremos la petición POST */
        $( '#boton' ).click(function() {
            $.ajax({
                url: <?= json_encode($_SERVER['PHP_SELF']) ?>,
                method: 'post',
                data: {
                    data: $( '#texto' ).val(),
                },
            }).done(function( datos ) {
                /* Mostramos el resultado de agregar los datos */
                $( '#resultado' ).text(datos);
                /* Limpiamos el campo de texto del formulario y colocamos el foco allí de nuevo */
                $( '#texto' ).val('').focus();
                /* Solicitamos al servidor que nos envíe los datos almacenados en la variable de sesión */
                $.ajax({
                    url: <?= json_encode($_SERVER['PHP_SELF']) ?>,
                    method: 'get',
                    data: {
                        actualizar: true,
                    },
                }).done(function( datos, resultado, xhr ) {
                    /* Mostramos el contenido de la variable de sesión tal y como nos la envía el PHP */
                    $( '#datos' ).text(xhr.responseText);
                    /* Por consola muestro los datos nativos de javascript */
                    console.log(datos);
                });
            });
        });
    </script>
</body>

</html>
    
answered by 16.08.2018 / 10:05
source
3

If what you are looking for is to send a variable of a form to add it to an array, the best thing you can do is store that variable with javascript and create an array, and then if you want to send it with php, you send it with a post method or you upload it directly to your database. If this is not worth you can try to pass the variable with GET. Hope this can help you!

var Tuarray = [];   //Creamos un array

//Cojemos la variable 
var variable = document.getElementById('tu_varible').value ; 

//Indentamos al final del array la variable separado por comas
Tuarray.push( variable + ","); 
    
answered by 14.08.2018 в 16:51