Codeigniter (CSRF) jQuery ajax problem Codeigniter (CSRF) jQuery ajax problem codeigniter codeigniter

Codeigniter (CSRF) jQuery ajax problem


Try (javascript):

var ID = $(".imageWrap:last").attr("id");var baseurl = "http://localhost/woho/";var doScroll = 1;var cct = $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");if (location.href == baseurl) {    $(window).scroll(function(){        if ($(window).scrollTop() > $('body').height() / 2) {            if(doScroll == 1) {                                   $.post(baseurl + 'ajax/images',{'id':ID,'<?php echo $this->security->get_csrf_token_name(); ?>': cct}, function(data) {                    alert(data);                    $("#wrapper_content").append(data);                    ID++;                });            }        }    });}


check value of your $config['csrf_token_name'] in /application/config/config.php as default is setted as csrf_test_name not csrf_token_name.

This decision if you not want to use PHP code in Javascript.

$.ajax({    url: 'some_url',    type: 'POST',    data: {csrf_test_name: $.cookie('csrf_cookie_name')}});

This code works fine.


If you use the form_open("/some",'id="some_form"') and form_close() , CI create a hidden input that keep the csrf_token_name and it value.

so , in your AJAX request , you can get the form by serialize it and send form !

For example:

<script>var _form = $("#some_form").serializeArray();$.ajax({    data: _form,    type: 'post',    url: '<?php echo base_url();?>some',    async: true,    success: function(output){        alert(output);    },    complete: function(output){},    fail: function(err){}});</script>

The CSRF always was my problem and by this method, it solved!!