How to change the class of the div according to Ajax’s response?

Asked

Viewed 414 times

0

Hello, I’m a beginner in PHP and Ajax and I’m creating a form for password recovery that validates the user’s email, date of birth and Cpf and sends the password to the registered email.

Node code below I made the request via Ajax and worked correctly, but I need to change the ID div class #errolog according to Ajax’s response that may be:

print "Verifique o e-mail, CPF e data de nascimento informados!";   

or

print ("Em breve você receberá a sua senha pelo e-mail $email <br><a href='login.php'>Login</a>");

Ajax:

<script type="text/javascript">
jQuery(document).ready(function(){
  jQuery('#verifica-senha').submit(function(){
    var dados = jQuery(this ).serialize();

    jQuery.ajax({
      type: "POST",
      url: "valida-recuperar.php",
      data: dados,
      success: function( data )
      {
        //alert( data );
        $('#errolog').css('display', 'block')
                     .html('<p>' + data + '</p>');  
      }
    });

    return false;
  });
});

valida-recover.php:

<?php 

include("conexao.php");


$email = $_POST['email'];
$cpf = $_POST['cpf'];
$nascimento = $_POST['nascimento']; 

$destinatario=$email;

$validadados = mysqli_query($con, "SELECT * FROM tb_cliente WHERE email = '{$email}' AND cpf = '{$cpf}' AND nascimento = '{$nascimento}'");

$rpes = mysqli_fetch_assoc($validadados);
$senha = $rpes['senha'];


$mensagem = "Olá, recebemos uma requisição de recuperação de senha. Sua senha é $senha !";

if(mysqli_num_rows($validadados)<=0) {
    print "Verifique o e-mail, CPF e data de nascimento informados!";   
    }
else {
    mail("$destinatario", "Recuperação de senha", "$mensagem","From: email");
    print ("Em breve você receberá a sua senha pelo e-mail $email <br><a href='login.php'>Login</a>");
}

?>

  • which class you want to change?

  • I use the bootstrap alert classes. I need you to successfully display class="Alert Alert-Success" and in case of error display class="Alert Alert-Danger".

1 answer

0


Retrieve the element via ID and add the new class:

jQuery('#errolog').addClass('nova-class');

Since you can have more than one class in HTML elements, adding a new class will not remove the old one. If you want to change a pre-existing one, it is important to remove the class.

jQuery('#errolog').removeClass('class-antiga').addClass('nova-class');

Do all this procedure within the method success and/or error ajax, as per your need.

Since you want to return conditional, it is important to validate (in javascript) the return before changing the class. In this way, I suggest using the return as json, because, you can return a flag containing the status and the success/error message.

echo json_encode(['success' => true , 'message' => 'Mensagem de sucesso']);

In the call of the method ajax, add the attribute dataType='json':

jQuery.ajax({
  /** demais atributos omitidos **/
    dataType='json'
    success: function( data )
    {
        var $errorLog = jQuery('#errolog');

        if (data.success)
        {
            $errorLog.addClass('success-class');
        }
        else
        {         
            $errorLog.addClass('error-class');
        }

        $errorLog.html(data.message)

    }
});

But it will depend on the logic you want to apply.

  • Thanks, Gabriel. One more question, on the page validate-recover.php how I define what is success or error?

  • You already have the prints with the error message and success. Just replace those prints with the respective json. When it succeeds status must be true. When it’s a mistake status must be false.

  • It worked, Gabriel. Thank you very much!

  • @Rodrigobianchini Excellent. Mark the answer as a solution to the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.