Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

php - Codeigniter (CSRF) jQuery ajax problem

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...