Issues with Codeigniter Ajax Post functionality

Hey everyone, I'm working on implementing a simple voting system for comments using jQuery Ajax to avoid page refreshing when someone likes or dislikes a comment.

Here is the jQuery code I have so far:

$(document).ready(function(){
    $(".vote-btn").click(function() {
        var voteId = this.id;
        var upOrDown = voteId.split('_');

        $.ajax({
            type: "POST",
            url: "http://localhost/Dropbox/cipr/index.php/demo",
            cache: false,
            dataType:'json',
            data:{'voteId='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
            success: function(response){
                try{
                    if(response=='true'){
                        var newValue = parseInt($("#"+voteId+'_result').text()) + 1;
                        $("#"+voteId+'_result').html(newValue);
                    }else{
                        alert('Sorry Unable to update..');
                    }
                }catch(e) {     
                    alert('Exception while request..');
                }
            },
            error: function(){                      
                alert('Error while request..');
            }
         });
    });
});

This is my Controller code in Demo.php:

<?php

class Demo extends CI_Controller {

function Demo(){
    parent::Controller();
    $this->load->model('sygjerimet');
}

public function index(){

    $voteId=  $this->input->post('voteId');
    $upOrDown=  $this->input->post('upOrDown');

    $status ="false";
    $updateRecords = 0;

    if($upOrDown=='voteup' || true){
        $updateRecords = $this->sygjerimet->updateUpVote($voteId);
    }else{
        $updateRecords = $this->sygjerimet->updateDownVote($voteId);
    }

    if($updateRecords>0){
        $status = "true";
    }
    echo $status;
}

And this is my model code in sygjerimet.php:

<?php 

Class Sygjerimet extends CI_Model
{

function shtoSygjerimin()
{
    $permbajtja = $this->input->post('idea');
    $data = array(
        'permbajtja' => $permbajtja
    );

    $this->db->insert('pr_sygjerimet', $data);

}

function updateDownVote($voteId){
    $sql = "UPDATE pr_sygjerimet set vote_down = vote_down+1 WHERE ID =?";
    $this->db->query($sql, array($voteId));
    return $this->db->affected_rows();
}

function updateUpVote($voteId){
    $sql = "UPDATE pr_sygjerimet set vote_up = vote_up+1 WHERE ID =?";
    $this->db->query($sql, array($voteId));
    return $this->db->affected_rows();
}

}

Finally, here is my view Code:

<?php
          $query = $this->db->query('SELECT * FROM pr_sygjerimet');

            foreach ($query->result() as $row)
            {
                echo "<div class='sygjerimi'>";
                echo htmlspecialchars($row->permbajtja);
                if(!$log_in):
                echo '<br>';
                echo ' <button id="'.$row->ID.'_votedown" class="vote-btn"><i class="fa fa-thumbs-down">'.htmlentities($row->vote_down).'</i></button> ';
                echo ' <button id="'.$row->ID.'_voteup" class="vote-btn"><i class="fa fa-thumbs-up">'.htmlentities($row->vote_up).'</i></button> ';
                endif;
                echo "</div>";
            }

        ?>

When I click the vote button, the following alert pops up:

alert('Error while request..');

If anyone can provide assistance, that would be greatly appreciated. Thank you!

Answer №1

It seems like the issue might be related to CI's CSRF protection feature. When using POST requests in CodeIgniter, it automatically checks for a hidden CSRF field. Since you are constructing the ajax post manually, this field is not being included, causing the error.

To resolve this, review the various $config['csrf_*'] settings in your config/config.php file. While disabling CSRF protection is an option, it is not recommended. Alternatively, you can serialize the form data using jQuery before sending it through ajax, which can help protect against CSRF attacks.

To confirm if CSRF protection is the cause of the problem, try temporarily disabling 'csrf_protection'. If the issue is resolved, re-enable it and adjust your JavaScript code to serialize the form data properly for ajax requests.

Answer №2

give this a shot

$.ajax({
    //retrieve the CSRF token in this manner
    data:{'<?php echo $this->security->get_csrf_token_name();?>':'<?php echo $this->security->get_csrf_hash();?>'},

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to match a String with the identifier of an array?

Hey there! I'm currently working on a project where I need to extract details for a specific item from one array by referencing another array. Here's the code snippet I have so far: foreach($json_items['result']['items'] as $ ...

Conceal a particular object from view by selecting it from the menu

I want to hide a specific element when the burger button is clicked. (See CaptureElementNoDisplay.PNG for the element to hide) When I click the burger button again to close the menu, I want the hidden item to be displayed once more. I've successfull ...

What is the best way to verify if an array of nullable integers is empty?

The information for this class is retrieved through an AJAX post request. public class FilterViewModel { public int?[] size { get; set; } public decimal? Price { get; set; } } When checking the price property, w ...

How does setting $.support.cors = true; affect the performance of ajax calls on browsers that do not support Cross-Origin Resource Sharing (

Hey everyone, I've encountered a situation where I need to make cross-domain AJAX requests, so I included the line "$.support.cors = true;" before my ajax calls. However, I'm noticing that for non-cross domain calls, my ajax requests don't ...

Determine in JQuery whether an element is positioned at the top of the screen

My webpage has a div that is initially positioned approximately 100px from the top of the browser window. As the user scrolls down, I aim to create an effect where this div remains in place until it reaches the very top of the screen. At that point, I pl ...

What are the steps for utilizing JSON data retrieved from an ajax response?

After successfully making an ajax request and receiving JSON data, I am struggling with how to use it effectively. The response I am getting looks like this: [{ "id": "5", "reviewID": "2389", "serviceID": "50707", "title": "well d ...

A Guide on Sending POST Data Using PHP

Within the same directory on a web server, I have two files: post.php and receive.php. The functionality of these files is as follows: post.php is responsible for posting a username and password, while receive.php receives this information and displays it ...

Encountering issues with HTMLPurifier on production environment

After successfully downloading and installing HTMLPurifier with zendframework2, I thoroughly tested its functionality and everything was working perfectly. However, when attempting to use it on the live system, it suddenly stopped functioning without any ...

JQuery Powered Text Analyzer

Our team is in the process of developing a text analyzer tool to review emails before sending them out. The goal is to involve all team members in selecting the best emails to send to clients: Implemented the following HTML code: <p class="sentence" ...

Switching a span's style in a jQuery accordion heading

To improve the usability of an accordion header, I am looking to add an expand/collapse button to the right side of each header. When clicked, this button should change from "expand" to "collapse". However, I have encountered some issues with the JavaScrip ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Ensure that at least one checkbox is selected by using custom validation in jQuery

My form has checkboxes for gender (male and female) and a set of checkboxes for days of the week (Monday to Sunday). I need to set validation rules so that at least one gender and one day is selected. Below is my jQuery code: $(document).ready(function( ...

Retrieve attendance data from Solution C1 attendance device using ZkLibrary PHP

Currently, I am in the process of developing a feature that involves retrieving attendance log data from the Solution C1 attendance machine using ZkLibrary. To achieve this, I am utilizing Laragon and have successfully enabled the SOAP and SOCKET extension ...

jQuery ceases to function once AJAX content is loaded

Exploring Options for Flexible Data Display I'm currently in the process of building a webpage that allows users to choose between different layouts for loading data. This includes the option to display data in either a list format or a card interfac ...

If a specific class is identified, add a border to the div when clicked using JavaScript

Is there a way to use javascript/jquery to add a border to a selected div? I have multiple rows with columns, and I want only one column per row to be highlighted with a border when clicked. Each row should have one column with a border, so it's clear ...

Callback not being triggered after AJAX request

I am currently troubleshooting some code that was not written by me, and I am facing challenges in understanding why an Ajax return is not triggering a Callback. The following code is responsible for attaching behaviors to the ajax functions: # Callback ...

What causes the discrepancy in CSS behavior between local and remote websites?

My chrome extension enhances facebook chatbox with jquery autocompletion. I am trying to make the suggestion list menu horizontal by modifying the jquery-ui.css. When changing display:block to display:inline, the list becomes horizontal in a local HTML fil ...

Upon selecting the username, the administrator has the ability to display the user profile

I have a list of users in my admin's page, and I want to be able to click on a username and get redirected to their profile. Here is the view of my admin page: <table class="table table-striped table-bordered table-condensed"& ...

The method insertFusionCharts cannot be called in Angular when using jQuery

I have integrated the following scripts into my angular project <script defer src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script src="assets/js/jquery.min.js"></script> <script ...

What is the Correct Method for Storing Form Data in a Database?

I've been working on a form using an MVC approach to insert data into a database with PDO. I have the addWine form, addWine controller, data access model, and wine class model. However, after submitting the form, nothing happens and the database remai ...