I have a hypothetical problem :
Mipagina.php
<?php if(isset($_GET['nombre']) && !empty($_GET['nombre'])) :?>
<?php $nombre = $_GET['nombre'];?>
Hola <?php echo $nombre;?>
<?php else:?>
<form id="formulario">
<input type="text" name="nombre"/>
<button type="submit" class="consultar">Consulta tu nombre</button>
</form>
<?php endif;?>
Script.js
$(document).on('click', '.consultar', function(e) {
e.preventDefault();
$('#formulario').submit();
});
It is essential to enter the name value, so that it shows information. In the case that there is no name, it will show a form to consult name.
So far everything seems to be correct, the problem begins:
I do not want to update the page when entering the name value, so I choose to use ajax.
Mipagina.php
<?php if(isset($_GET['nombre']) && !empty($_GET['nombre'])) :?>
<?php $id = $_GET['nombre'];?>
Hola <?php echo $nombre;?>
<?php else:?>
<form id="formulario">
<input type="text" class="nombre" name="nombre"/>
<button type="submit" class="consultar">Consulta tu nombre</button>
</form>
<div id="resultado-ajax"></div>
<?php endif;?>
Ajax.php
<?php $nombre = $_POST['nombre'];
echo $nombre;?>
Script.js
$(document).on('click', '.consultar', function(e) {
e.preventDefault();
consulta_Ajax();
});
function consulta_Ajax() {
nombre = $('.nombre').val();
$.post({
url: 'Ajax.php',
dataType: 'html',
nombre: nombre,
}).done(function(respuesta) {
$('#formulario').hide(); // esconde formulario
$('#resultado-ajax').html(respuesta); // imprime respuesta
window.history.replaceState({} , '' , '?nombre='+respuesta);
});
}
I have two actions: The first is when the user enters: Mipagina.php? Name = Juanito and the second, in case you do not enter your name, consult it using the form.
This works, but the question is: Is there another method to achieve this? Is it necessary to have to write the result twice? URL and Ajax?
Ok!