Estoy revisando este formulario en busca de errores usando el código PHP que se encuentra en el mismo archivo index.php :
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <?php if(!empty($formErrors)){ ?> <div id="errors"> <?php foreach($formErrors as $error) { echo '* ' . $error . '.<br/>';} ?> </div> <?php } ?> <input type="text" name="firstname"> <input type="submit" value="send"> </form>El código PHP es el siguiente:
<?php if($_SERVER['REQUEST_METHOD'] == 'POST'){ $fname = $_POST['firstname']; $formErrors = array(); if(strlen($fname) < 2 ){ $formErrors[] = "First name must be longer than 1 character"; } } ?>Todo funciona bien hasta este punto, excepto que quiero evitar que la página se desplace hacia arriba al enviar el formulario. Por lo tanto, utilicé ajax para resolver este problema:
$("form").submit(function(e){ e.preventDefault(); $.ajax({ type: $(this).attr("method"), url: $(this).attr("action"), data: $(this).serialize() }); });Ahora los errores de formulario ya no se mostrarán, que no es lo que quiero. ¿Cómo puedo volver a mostrar los errores sin descartar ajax? Gracias.
Aunque esta no es la mejor manera, puede repetir el JSON del archivo y mostrar esos errores en su función ajax como se muestra a continuación:
Interfaz (ajax):
$("form").submit(function(e){ e.preventDefault(); $.ajax({ type: $(this).attr("method"), url: $(this).attr("action"), data: $(this).serialize() + '&ajax=1', dataType:'json', success: function(res){ if(res.success === false){ $('#errors').html('<ul><li>' + res.errors.join('</li><li>') + '</li></ul>'); }else{ $('#errors').html(''); } } }); });back-end:
<?php if($_SERVER['REQUEST_METHOD'] == 'POST'){ $fname = $_POST['firstname']; $formErrors = array(); if(strlen($fname) < 2 ){ $formErrors[] = "First name must be longer than 1 character"; } // add this additional check if(($_POST['ajax'] ?? 'N/A') == '1'){ echo json_encode(['success' => false,'errors' => $formErrors]); exit; // since we will only send the JSON back to the browser, not the entire form } } ?> Cambie su código de formulario a esto (agregando un errors div siempre por defecto):
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <div id="errors"></div> <input type="text" name="firstname"> <input type="submit" value="send"> </form>