Codeigniter (CSRF) jQuery ajax problem

17,361

Solution 1

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

Solution 2

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.

Solution 3

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!!

Share:
17,361
Dexty
Author by

Dexty

Updated on July 19, 2022

Comments

  • Dexty
    Dexty almost 2 years

    I’ve got a issue here, i keep getting a error when i try to post something with ajax (POST). I know it is the CSRF that gives me these problems and I’ve been tried back and forth trying to find a solution. However, i hope somebody here can help me out!

    This is the error i keep getting (from google chrome inspector),

    *Failed to load resource: the server responded with a status of 500 (Internal Server Error) XHR finished loading: "http://localhost/woho/ajax/images".*

    PHP (Controller)

    class Ajax extends CI_Controller {
    
        function images() {
    
            echo 'Hello World';
    
        }
    
    }
    

    Javascript

    var ID = $(".imageWrap:last").attr("id");
    var baseurl = "http://localhost/woho/";
    var doScroll = 1;
    var cct = $.cookie('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, 'csrf_token_name': cct}, function(data) {
                        alert(data);
                        $("#wrapper_content").append(data);
                        ID++;
                    });
                }
            }
        });
    }
    

    my CCT var from javascript gives me the correct token or "hash" but when the javascript sends the ajax request codeigniter returns an error like,

    An Error Was Encountered The action you have requested is not allowed.

    How can i fix this? do i need to validate the CSRF Token or something in my controller?

    I'm using Codeigniter 2.0.3

  • Dexty
    Dexty over 12 years
    OMFG, Ofc i need to use the actual name, and not the var. Haha, man, thanks! Tunnel vision next?
  • M. Prokhorov
    M. Prokhorov about 6 years
    I think this is the same answer as the other ones, including the accepted.