Search code examples
ajaxcodeignitercodeigniter-4

Ajax login form getting error 404 in Codeigniter 4


I have problem with my ajax code in codeigniter 4. I have a login form. The codes I use are working fine in codeigniter 3. Here is the codes.

PHP


public function login()
{
    if (! $this->request->isAJAX()) {
        //show404();
    }
    $this->validation->setRules([
        'email' => [
            'label'  => 'Email',
            'rules'  => 'required',
            'errors' => [
                'required' => '{field} some message.'
            ]
        ],
        'password' => [
            'label'  => 'Password',
            'rules'  => 'required|min_length[6]',
            'errors' => [
                'required' => '{field} some message.',
                'min_length' => '{field} some message.'
            ]
        ]
    ]);

    if ($this->validation->run() == FALSE) {
        if ($this->validation->hasError('email'))
        {
            echo sprintf('{"status":false,"message":"%s"}', addslashes((preg_replace('/\s+/', ' ', $this->validation->getError('email')))));
        }

        if ($this->validation->hasError('password'))
        {
            echo sprintf('{"status":false,"message":"%s"}', addslashes((preg_replace('/\s+/', ' ', $this->validation->getError('password')))));
        }
    }else {
        echo sprintf('{"status":true,"message":"%s"}', '<p>Success</p>');
    }
    exit();
}

HTML


<form action="<?= DOMAIN_NAME.'admin/login'; ?>" id="adminLoginFrom" name="adminLoginFrom" method="post" enctype="multipart/form-data">

JS

I posted the bottom because i have a feeling perhaps one of these linked files may be in conflict with the ajax block i have written below


$("#adminLoginFrom").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    var url = form.attr('action');
    $.ajax({
        url: url,
        type: "POST",
        data: $('#adminLoginFrom').serialize(),
        dataType: "json",
        success: function( response ) {
            console.log(data);
            console.log(response.success);
        }
    });
});

ROUTE.PHP


$routes->get('admin/login', 'Admin/Ajax::login');

Solution

  • In codeigniter4 you have to put the same method that you put in the ajax request, in this case POST

    $routes->post('admin/login', 'Admin/Ajax::login');