Php – CodeIgniter AJAX: POST not working, GET works fine


Fiddling inside CodeIgniter and trying to get a grip on it all as I've never worked with AJAX before.

For some reason, my AJAX is working perfectly when I use the GET method, but if I switch it over to the POST method, it stops working.

My JS:


    $('.love').click(function(event) {


            type: 'GET',
            url: base_url + '/ajax/love_forum_post',
            data: { post_id: 2, user_id: 1, ajax: 1 },


        return false;




function love_forum_post()


    $post_id = $this->input->get('post_id');
    $user_id = $this->input->get('user_id');
    $is_ajax = $this->input->get('ajax');

    if ($is_ajax)


        $this->forums_model->add_love($post_id, $user_id);


    // If someone tries to access the AJAX function directly.



        redirect('', 'location');



If I switch the type to 'POST' inside my JS and then catch it on the other end with $this->input->post() it doesn't work.

Any suggestions?

Best Solution

I have tested your code in 2 scenarios: first - without csrf protection, and I see no reason for your code not to run properly. To be able to test it easier, append $.ajax call with success response. Something like this

success: function(response) {

And add response to your love_forum_post method.

echo print_r($this->input->post(), true);

This would give you clean view of what it going on in your method.

In my installation everything works just fine.

Second scenario is with csrf protection. In this case add new param to your post object.

<?php if ($this->config->item('csrf_protection') === true) : ?>
            post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>'; 
<?php endif ?>

This would make CI accept post from this url.

Hopefuly it would help. Cheers

Related Question