CodeIgniter Forums
Call Ajax - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Call Ajax (/showthread.php?tid=77742)



Call Ajax - guilhermepalange - 10-13-2020

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)



RE: Call Ajax - InsiteFX - 10-14-2020

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

How to Send AJAX request with CSRF token in CodeIgniter 4


RE: Call Ajax - nc03061981 - 10-14-2020

(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


RE: Call Ajax - includebeer - 10-17-2020

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.


RE: Call Ajax - InsiteFX - 10-17-2020

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'); 



RE: Call Ajax - includebeer - 10-18-2020

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


RE: Call Ajax - InsiteFX - 10-18-2020

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.