Encountering a 403 (Forbidden) error when making a POST call using XMLHttpRequest in CodeIgniter 3 is likely due to

I'm attempting to execute an ajax call using basic javascript XMLHttpRequest() to a codeigniter controller that has activated csrf and regeneration. It only functions properly if I gather the data and token from a form; otherwise, I receive a 403 (Forbidden) error. Here is the JS:

function test_ajax() {
var ajax = new XMLHttpRequest();
    var data = {'csrf_test_name':csrfToken} ;
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", base_url+'admin/test_ajax');
ajax.setRequestHeader('X-Requested-With', 'XMLHTTPRequest');
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;   charset=UTF-8');
ajax.setRequestHeader('csrf_test_name', csrfToken);
ajax.responseType = "json";
ajax.send(data);

function completeHandler() {
    console.log(event.target.response);
}
function errorHandler() {
}
function abortHandler() {
 }
}

And here is the codeigniter controller:

class Admin extends CI_Controller{
public function __construct(){
    parent::__construct();
    $this->load->library('session');
    $this->load->helper('url_helper');
    $this->load->helper('security');
    $this->load->helper('cookie');
 }
public function test_ajax(){
  $x = array('test1','test2');
    echo json_encode($x);
    //var_dump($x);
}
}

I attempted to include the token in both the header and the data sent, but neither method worked even on the initial request. If possible, I would prefer a solution where the token is included in the data and not the header (as some browsers have trouble with setting headers). Please provide solutions without using jQuery, as I specifically need this functionality to work with plain javascript. Thank you in advance.

Answer №1

After some exploring, I stumbled upon the answer that could potentially assist others. It appears that in order for the controller to receive the data correctly, it must be serialized in the following format:

let serializedData = "csrf_test_name=" + csrfToken;

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

Validating a single field for City, State, and ZIP in jQuery/JavaScript

I am trying to validate an input field that requires City, State (two letter abbreviation), and ZIP code (5 numeric digits) in the format 'City, State ZIP'. Could someone please help me with validating this specific format and characters? Appre ...

Forward traffic to https using Node.js

I am attempting to redirect users from http://my-domain to https://my-domain. My initial thought was to utilize the .htaccess file, but it seems that this method does not work with Node.js. The following function is my effort to replicate the logic of .ht ...

Exploring the power of Vue 3 and Vuex with Typescript to access class methods

Can Vuex state be used to access class methods? For example, in this scenario, I am attempting to invoke fullName() to show the user's formatted name. TypeError: store.state.user.fullName is not a function Classes export class User { constructo ...

Encountering an error stating that 'coordinates should consist of an array with two or more positions'

Utilizing turf.js to generate a line depicting the path of an individual while their location is tracked. An array of coordinate arrays resembling Turf.js (lineString) is causing this error: Uncaught Error: coordinates must be an array of two or more posi ...

Counting each item with jQuery and assigning them numbers 02, 03, 04, etc., with the exception of the first item which will display as "Up Next

I'm still learning jQuery and here's the code I've put together after researching on stackoverflow and other platforms: var counter = 1; $('.next-page .nav-item').each(function () { if ($(this, ':gt(0)')) { $(this ...

Can JavaScript be used to bypass AJAX cookies?

Is there a way in JavaScript to programmatically ignore server-sent cookies without adjusting browser settings? We have implemented plugins on our web server that periodically update our security cookie, resulting in compatibility issues with certain URLs ...

The issue encountered while attempting to utilize jspdf for exporting data

Currently, I am working on developing a web application using angularJS in combination with asp.net. My main goal is to export data into a PDF file, but unfortunately, I am facing some challenges in achieving this. While browsing on StackOverflow, I came ...

When I try to use Node.js and Express, I encounter an issue where I receive the

I recently developed a basic application. Everything was running smoothly until I decided to organize the code using an MVC template. However, now when you visit localhost:3000/add-service, you are greeted with a "Cannot Get /add-service" error message. W ...

Synchronizing client information in real-time: tips, tricks, and expert advice

Currently, I am developing a PHP backend and utilizing JS/Jquery for the front end of an application that aims to facilitate near real-time communication among users. My main concern right now is determining the most effective approach to achieve this goal ...

When transitioning from another page, the header will cover a portion of the section

I am facing a specific issue that I need help with. My goal is to have the navigation bar link to different sections of a single page when clicked. For example, clicking on "Contact" should take the user to the contact section, and then if they click on "A ...

Trouble with Vue 3 watch not persisting after page refresh

Attempting to create a Vue application that supports two languages, utilizing local storage and store to store the selected language. Initially, everything appears to be functioning correctly. After the user logs in, the default language is displayed in b ...

Generating unique URLs with Express.js using MongoDB IDs

Hello, I am a beginner with node.js and express.js. I am in the process of developing a todo application that operates as follows: I have a mongodb database of Todos containing different todo lists. These lists contain tasks categorized as either unfinishe ...

Angular 9 date input and selection

I am currently troubleshooting why the attribute value on an input type date is not working with Angular 9. <input type="date" [max]="dateConfig.max" [min]="dateConfig.min" name="date" [value]="dateConfig.val ...

Should I wait for my state to be updated with new information before triggering the render function?

Can someone assist me with restructuring the code below to ensure that the information in the data array is displayed on the initial page load? async componentDidMount() { const { id } = this.props.match.params const soccerApi = axio ...

Solving repeated function firing with ng-checked in an AngularJS ng-repeat loop

In the HTML code below, there is an ng-repeat that creates checkboxes: <span ng-repeat="name in $ctrl.widgetSelectorNames" class="widget-selectors"> <label class="checkbox" for="{{name}}"> <input type="checkbox" value="{ ...

Guidelines for sorting through items in Vue 3

In the past, Vue 2 allowed us to easily filter items using the | and filters syntax. However, this method is no longer supported in Vue 3. Instead, we now use the "computed" property to transform a single value into another. But what about changing values ...

The Popover fails to attach itself to the element that triggered it

It appears that my Twitter Bootstrap popovers are experiencing positioning issues when the triggering element is inside a container with the style -ms-overflow-y: auto; (a scrollable element within the window). As I scroll the element, the popover does no ...

Webpack is having trouble resolving modules from the subdirectory of a package

I am facing an issue with a package I am working on, which is structured as follows: - lib/ -- moduleA/ ---- index.js -- moduleB/ ---- index.js - src/ -- moduleA/ -- moduleB/ The package.json file specifies: "main": "./lib" When trying to import a spec ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...

Using Angular.js to fetch information from a MySQL database

I'm currently trying to retrieve data from a MySQL database in an Angular.js application. I have gone through multiple tutorials, but unfortunately, none of them have been successful for me. I have a PHP script that returns a JSON array with example ...