Welcome Guest, Not a member yet? Register   Sign In
Call Ajax
#1

hello.

I'm trying to make a post with ajax and I get the error 500, could someone help me

My Routes
PHP Code:
$routes->get('app-admin''\Modules\admin\Controllers\Auth::login');

 
$routes->get('app-admin/auth/authenticate''\Modules\admin\Controllers\Auth::authenticate');
 
$routes->get('app-admin/auth/recovery''\Modules\admin\Controllers\Auth::recovery');
 
$routes->get('app-admin/auth/logout''\Modules\admin\Controllers\Auth::logout');
 
$routes->get('app-admin/auth/update_password''\Modules\admin\Controllers\Auth::update_password'); 

My login.js
Code:
$(document).ready(function(){

    var APP_URL = $("#app_url").data("url");

    $("#login").validate({
        errorContainer: "#erroLogin",
        errorLabelContainer: "#erroLogin",
        wrapper: "p",
        errorElement: 'p',
        ignore: [],
        rules: {
            senha: "required",
            email: {
                required: true,
                email: true
            }
        },
        messages: {
            senha: "Informe sua senha",
            email: {
                required: "Informe seu email",
                email: "Informe um email válido"
            }
        },
        submitHandler: function(form) {
            var submitTxt = $("#submitLogin").html();
            $("#submitLogin").html("Aguarde...");
            var request = $.ajax({
                url: APP_URL+"/auth/authenticate/",
                method: "POST",
                data: $(form).serialize(),
                cache: false,
                processData: false,
                dataType: "JSON"
            });
            request.done(function( msg ) {
                if(msg.status != 200){
                    div = '<div class="alert alert-warning alert-dismissable" style="margin-top:10px;">';
                    div += '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>';
                    div +=  msg.response;    
                    div += '</div>';
                    $("#submitLogin").html(submitTxt);
                    $( "#erroLogin" ).html( div ).css({'display': 'block'});
                }else{
                    $("#submitLogin").html( msg.response);
                    location.href= APP_URL+'/dashboard';
                }
            });
            request.fail(function( jqXHR, textStatus ) {
                $("#submitLogin").html(submitTxt);
                console.log( "Request failed: " + textStatus );
            });

            return false;
        }
    });

    
});

Login.php
PHP Code:
<?php echo view('\Modules\admin\Views\template\head'?>

<div class="flex-row align-items-center">


    <div class="container">
        <div class="row justify-content-center">
          <div class="col-md-5">
            <div class="card-group" style="margin-top: 20%;">
              <div class="card p-4">
                <div class="card-body">


                     <form id="login" method="POST" action="">
                      <h1>Login</h1>
                      <p class="text-muted">Olá, seja bem vindo.</p>
                      <div class="input-group mb-3">
                        <div class="input-group-prepend">
                          <span class="input-group-text"><i class="icon-user"></i></span>
                        </div>
                        <input type="email" class="form-control" id="email" name="email">
                      </div>
                      <div class="input-group mb-4">
                        <div class="input-group-prepend">
                          <span class="input-group-text"><i class="icon-lock"></i></span>
                        </div>
                        <input type="password" class="form-control" id="senha" name="senha">
                      </div>
                      <div class="row">
                        <div class="col-6">
                          <button type="submit" id="submitLogin" class="btn btn-primary px-4">Entrar</button>
                        </div>
                        <div class="col-6 text-right">
                          <a href="admin\recovery" class="btn btn-link px-0">Esqueceu a senha?</a>
                        </div>
                      </div>
                      </form>
                      <div id="erroLogin"></div>
                </div>
              </div>

            </div>
          </div>
        </div>
    </div>

    
</div>
<?php 
$js 
= array('/resource/admin/js/custom/login.js'); 
echo 
view('\Modules\admin\Views\template\footer', array('js'=>$js'login'=>true)); 
?>

My Controller

PHP Code:
public function login(){
        echo 
view('\Modules\admin\Views\auth\login');
    }


    public function 
authenticate(){


        if (
$this->request->isAJAX()) {
            
$prodID service('request')->getPost('id');
            
var_dump($this->request->getPost('id'));
        } 
        if(!
$this->input->is_ajax_request()){
            
$this->output("Forbidden"403);
        }

        
$email $this->input->post('email');
        
$senha $this->input->post('senha');

        
$email strtolower(trimstrip_tags$email ) ));
        if(!
filter_var($emailFILTER_VALIDATE_EMAIL)){
            
$this->output("O email informado é inválido."404);
        }            

        if(empty(
$senha)){
            
$this->output("Informe a senha."404);
        }

        
$user $this->_model->UserByEmailSenha$emailsha1($senha) );

        if(!
$user){
            
$this->output("Nenhum usuário encontrado para o email e senha informados."404);
        }

        if(
$user['ativo'] == 0){
            
$this->output("Sua conta se encontra desativada."404);
        }

        
$sessao = array(
            
'id'=> $user['id'],
            
'nome'=> $user['nome'],
            
'email'=> $user['email']
        );

        foreach (
$sessao as $key => $value) {
            
$this->session->set_userdata($key$value);
        }

        if(
$this->session->id){
            
$this->output("Redirecionando..."200);
        }else{
            
$this->output("Falha na autenticação. Tente novamente."404);
        }

    } 

And error:
Code:
jquery.min.js:4 POST http://localhost:8090/app-admin/auth/authenticate 500 (Internal Server Error)
Reply
#2

Maybe this will give you some insight into how it works.

How to Send AJAX request with CSRF token in CodeIgniter 4
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(10-14-2020, 12:32 PM)InsiteFX Wrote: Maybe this will give you some insight into how it works.

How to Send AJAX request with CSRF token in CodeIgniter 4

Thanks for more knowledges

Learning CI4 from my works, from errors and how to fix bugs in the community

Love CI & Thanks CI Teams

Reply
#4

Code:
jquery.min.js:4 POST http://localhost:8090/app-admin/auth/authenticate 500 (Internal Server Error)

Look at the log file. It will give you a lot more information to find what is causing this error. You can also look at the output returned by the server in your browser’s console.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#5

Also I think his routes are wrong he should be using post on the ones returning post data.

PHP Code:
$routes->get('app-admin''\Modules\admin\Controllers\Auth::login');

$routes->post('app-admin/auth/authenticate''\Modules\admin\Controllers\Auth::authenticate');
$routes->post('app-admin/auth/recovery''\Modules\admin\Controllers\Auth::recovery');
$routes->get('app-admin/auth/logout''\Modules\admin\Controllers\Auth::logout');
$routes->post('app-admin/auth/update_password''\Modules\admin\Controllers\Auth::update_password'); 
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#6

(10-17-2020, 11:04 AM)InsiteFX Wrote: Also I think his routes are wrong he should be using post on the ones returning post data.

Yes, definitely.

But people need to learn how to debug on their own instead of always been spoon fed all the answers. Looking for a detailed error message and a stack trace is the first thing to do. Then if you have no idea, ask for help.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#7

Yes, I agree but some users have never done this before so they need a helping hand.

I usually go by how many posts they have to tell if their new users or not.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB