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.