Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7648967
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T10:50:54+00:00 2026-05-31T10:50:54+00:00

I’m trying to use AJAX and JSON inside CodeIgniter. I’ve never used either technologies

  • 0

I’m trying to use AJAX and JSON inside CodeIgniter. I’ve never used either technologies before, but I’m starting to get a handle on it.

Here’s what I’m trying to achieve…

On my site, users can “love” other user’s posts on the forums. I would like the counter next to the love link to update automatically using AJAX and JSON.

Here is the relevant code:

VIEW:
A simple HTML link used for adding a love to the count.

<p><a href="#" class="love"><?php if ($post->love) { echo $post->love; } else { echo 0; } ?></a></p>

JQUERY:
Called when the link above is clicked. It calls the /ajax/love_forum_post function (code below) and passes through some data for the post and active user ID’s (2 and 1, which I’ve hard coded in for the time being). It then increments the count by 1 and switches the class.

$(document).ready(function(){

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

        $.ajax({

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

        });

        var num = parseInt($.trim($(this).html()));
        $(this).html(++num).toggleClass('loved');

        return false;

    });

});

CONTROLLER:
The function called by Ajax when the link is clicked.

public 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->load->model('forums_model');
    $total_loves = $this->forums_model->add_love($post_id, $user_id);
    echo json_encode($total_loves);

}

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

else

{

    redirect('', 'location');

}

MODEL:
And finally, the model function that is called to add a love to the database and return the new count, which is grabbed in the controller using JSON (I think).

function add_love($post_id, $user_id)

{

    // Check that the user has not already loved the post.

    $this->db->select('id');
    $this->db->from('post_rating');
    $this->db->where('post_id', $post_id);
    $this->db->where('user_id', $user_id);
    $query = $this->db->get();

    // If they have not already loved the post.

    if ( ! $query->num_rows() > 0)

    {

        $data = array(
            'post_id' => $post_id,
            'user_id' => $user_id,
            'rating' => 1
        );

        // If a new love is added, return the new count.

        if ($this->db->insert('post_rating', $data))

        {

            $this->db->select('id');
            $this->db->from('post_rating');
            $this->db->where('post_id', $post_id);
            $this->db->where('user_id', $user_id);
            $query = $this->db->get();

            return $query->num_rows();

        }

    }

}

So…

  1. How would I fetch this new love count with JSON and make my counter show the new total?
  2. Is there anything else in my code that should be changed/improved?
  3. And finally, I am unable to use the POST method as I have CSRF protection enabled. How could I alter my code to allow the POST method to be used instead of GET? Or is the GET method okay for this?

Thanks, I’m still very green when it comes to PHP, CodeIgniter, AJAX and jQuery. Enjoying the challenge though!

  • Tim.
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T10:50:55+00:00Added an answer on May 31, 2026 at 10:50 am

    1. How would I fetch this new love count with JSON and make my counter show the new total?

    You’re (almost) already doing this. Your json_encode()‘ed return value is an integer. Try this instead:

    <?php
    //...
    echo json_encode(array('total_loves' => $total_loves));
    //...
    

    Then, in your view…

    <?php
    // Probably better to pass in these values from
    // the controller, but this should work...
    $CI =& get_instance();
    $token = $CI->security->get_csrf_token_name();
    $hash  = $CI->security->get_csrf_hash();
    ?>
    
    $.ajax({
        type: 'POST',
        url: base_url + '/ajax/love_forum_post',
        data: {
            post_id: 2,
            user_id: 1,
            '<?= $token; ?>': '<?= $hash; ?>' // this takes care of the CSRF issue
        },
        dataType: 'json',
        success: function(response) {
            alert(response.total_loves); // do something with the return value...
        }
    });
    

    2. Is there anything else in my code that should be changed/improved?

    Rather than passing in an “ajax” parameter, use the Input class to tell whether it’s an AJAX request…

    <?php
    $is_ajax = $this->input->is_ajax_request();
    

    3. And finally, I am unable to use the POST method as I have CSRF protection enabled. How could I alter my code to allow the POST method to be used instead of GET? Or is the GET method okay for this?

    I would strongly recommend using POST, rather than GET, as GET requests are assumed not to change any data. (Google “idempotence” for a better understanding of this concept…)

    As for CSRF protection, I included a solution in the answer to your first question (see above).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am trying to render a haml file in a javascript response like so:
Seemingly simple, but I cannot find anything relevant on the web. What is the
I have a French site that I want to parse, but am running into

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.