Question: XMLHttpRequest() POST call in codeigniter 3 403 (Forbidden) due to csrf protection

Question

XMLHttpRequest() POST call in codeigniter 3 403 (Forbidden) due to csrf protection

Answers 1
Added at 2016-12-31 08:12
Tags
Question

I'm trying to make a ajax call using plain javascript XMLHttpRequest() to a codeigniter controller that has csrf and regeneration activated. it works only if I colect the data and token from a form , otherwise I get 403 (Forbidden). 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 controller in codeigniter:

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);
}
}

So I tried to add the token in the header also in the data to be sent, neither works not even from the first call. I would prefer a solution to make it work by including the token in the data and not in the header if possible (some browser have problmes with setting headers). Please no jQuery solutions, I need this one to work using plain javascript. Thanks in advance.

Answers to

XMLHttpRequest() POST call in codeigniter 3 403 (Forbidden) due to csrf protection

nr: #1 dodano: 2016-12-31 10:12

I found the solution , maybe this will help somebody, the data sent to the controller needs to be serialized in this format:

var data = "csrf_test_name="+csrfToken;
Source Show
◀ Wstecz