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>