I need to pass an array / JSON / Ajax variable to a PHP variable, so that I can manage it in my file. I currently have this in index.php:
<script type="text/javascript">
$("#enviar").click(function(e) {
e.preventDefault();
var nombre = $("#nombre").val(),
apellido = $("#apellido").val(),
edad = $("#edad").val(),
//"nombre del parámetro POST":valor (el cual es el objeto guardado en las variables de arriba)
datos = {"nombre":nombre, "apellido":apellido,"edad":edad};
$.ajax({
url: "procesa.php",
type: "POST",
dataType: 'json',
data: datos
}).done(function(respuesta){
if (respuesta.estado === "ok") {
$('#myName').text(respuesta.nombre);
$('#myApellido').text(respuesta.apellido);
$('#myEdad').text(respuesta.edad);
}
});
});
</script>
<form id="form">
<input type="text" id="nombre" placeholder="Nombre" accept="text/plain"><br><br>
<input type="text" id="apellido" placeholder="Apellido" accept="text/plain"><br><br>
<input type="number" id="edad" placeholder="Edad" accept="text/plain">
<input type="submit" id="enviar" value="Enviar">
</form>
<hr>
<p>Name: <span id="myName"></span></p>
<p>Apellido: <span id="myApellido"></span></p>
<p>Edad: <span id="myEdad"></span></p>
And in the file procesa.php, ak final I have:
header('Content-Type: application/json');
//Guardamos los datos en un array
$datos = array(
'estado' => 'ok',
'nombre' => $nombre,
'apellido' => $apellido,
'edad' => $edad
);
//Devolvemos el array pasado a JSON como objeto
echo json_encode($datos, JSON_FORCE_OBJECT);
Question of the million is, HOW TO GET IN A PHP VARIABLE MY VARIABLE JSON RESPONSE? Something like this: $ mynewnombre = $ _POST ["which variable to capture"]; Will it be? Because I currently put it in an id of a span and it works perfect, but it's not what I'm looking for. Any help?