Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
El formulario no muestra errores si se usa ajax

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!