Onur Şevik
Onur Şevik

Reputation: 15

I get 'page not found' error with Codeigniter and AJAX request

I'm developing a project with CodeIgniter but i have a problem when sending request with jQuery AJAX. My default controller is:

$route['default_controller'] = "test";

and here is my test controller:

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class test extends CI_Controller {

    function __construct() {
        parent::__construct();
    }
    public function login_with() {
        echo "1";
    }
}

and here is my AJAX request:

$(function() {
    $('#login_with').click(function() {
        $.ajax({
            type: "post",
            url: "<?= base_url('test/login_with') ?>",
            data:"login=1",
            success:function(ajax_success){
                alert(ajax_success);
            }
        });
    });
});

finally here is my .htaccess file:

DirectoryIndex index.php
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|robots\.txt)
RewriteRule ^(.*)$ index.php?/$1 [L]

What is wrong here? I'm getting 404 page not found error when request has been sent.

Upvotes: 0

Views: 1357

Answers (3)

Zura Sekhniashvili
Zura Sekhniashvili

Reputation: 1167

Try this

$(function() {
    $('#login_with').click(function() {
        $.ajax({
            type: "post",
            url: window.location.origin+"/test/login_with",
            data:"login=1",
            success:function(ajax_success){
                alert(ajax_success);
            }
        });
    });
});

Upvotes: 0

Filippo oretti
Filippo oretti

Reputation: 49873

First check if your website has mod_rewrite enabled then check if you have this in your config/config.php

$config['index_page'] = ''

i suggest you to try this htaccess then:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

Upvotes: 1

GautamD31
GautamD31

Reputation: 28773

Try with site_url() like

$.ajax({
        type: "post",
        url: "<?= site_url('test/login_with'); ?>",
        data:"login=1",
        success:function(ajax_success){
            alert(ajax_success);
        }
    });

And try to put exit after echo like

public function login_with() {
    echo "1";
    exit;
}

Upvotes: 1

Related Questions