Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
Form is not displaying errors if ajax is used

I'm checking this form for errors using PHP code which is on the same index.php file:

<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>

The PHP code is as follows:

<?php 
    if($_SERVER['REQUEST_METHOD'] == 'POST'){

         $fname = $_POST['firstname'];
         $formErrors = array();

            if(strlen($fname) < 2 ){
                $formErrors[] = "First name must be longer than 1 character";
            }
}
?>

Everything is working fine up to this point, except that I want to prevent the page from scrolling to the top upon form submission. Therefore i used ajax to solve this problem:

$("form").submit(function(e){
    e.preventDefault();
    $.ajax({
      type: $(this).attr("method"),
      url: $(this).attr("action"),
      data: $(this).serialize()
    });
  });

Now the form errors won't display anymore, which is not what I want. How can I show the errors again while not discarding ajax? Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Although this isn't the best way, you can echo the JSON from the file and display those errors in your ajax function like below:

FrontEnd(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('');   
        }
      } 
    });
  });

Backend:

<?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
        } 
}
?>

Change your form code to this(adding a errors div always by default):

<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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda