Dangling Cruze
Dangling Cruze

Reputation: 3443

Ajax jquery url access denied in codeigniter

$.ajax({
        type: 'POST',
        url: '/ci_practice/blog/reviews',
        data: 'res_id='+res_id,
        success: function(data){
            $('#screen-overlay').show(slow);
            $('#screen-overlay').html(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        console.log(xhr.responseText);
        alert(thrownError);
    }
});

This throws me a 500 error. There is a problem in accessing the function reviews as shown by console.log(xhr.responseText); in console.

How should i assign value to url in ajax to perform this in a codeigniter way. I have jQuery in a different file : ajax.js

Will appreciate your response. Thank You.

Upvotes: 0

Views: 2547

Answers (2)

Dangling Cruze
Dangling Cruze

Reputation: 3443

Problem was the CSRF enabled in my config file! But disabling it is a wrong step.

This link : Codeigniter Ajax CSRF Problem actually solved my problem. Using this code :

var post_data = {
            'res_id' : res_id,
            '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
        };

This just adds a CSRF security key which is needed by default by every POST method while submitting due to CSRF Enabled.

Upvotes: 1

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

You should contain the base_url with controller name / then function name you want to access

$.ajax({
    type: 'POST',
    url: '<?php echo base_url(); ?>/controllername/function',
    data: 'res_id='+res_id,
    success: function(data){
        $('#screen-overlay').show(slow);
        $('#screen-overlay').html(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    console.log(xhr.responseText);
    alert(thrownError);
}

});

in you case i think blog is the controller and reviews is a function so it should look like this url: '<?php echo base_url(); ?>/blog/reviews',

For Forbidden Error 403 forbidden error might be due to a faulty .htaccess rewrite you should remove the index.php url you .htaccess file should contain

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Your config.php should contain this

$config['index_page'] = "";

$config['uri_protocol'] = 'AUTO';

Upvotes: 1

Related Questions