Welcome Guest, Not a member yet? Register   Sign In
Ajax POST and CSRF
#1

I really have tried several ways to send post data via ajax. CSRF is blocking me and I dont want to disable or exclude the controller from CSRF check.

Way One:

Code:
function sendrow(e){
var working=$('#working');
var value="<?php echo $this->security->get_csrf_hash();?>";
var name="<?php echo $this->security->get_csrf_token_name(); ?>";
working.html('');
var path='http://localhost/ph/ctrl/process';
working.html('<img src="http://localhost/ph/assets/img/loading24.gif/>"').load(path, {name:value,'e':e}, function(data, status, response) {
                                                                                                                                                
            working.html("");    
                    if(status!='error'){
                        alert(true);
                        
                    }
                        else {
                            alert('server error');
                        }
            
            
                });
}

Method Two:

Code:
function sendrow(e){

$.ajax({
            type: "post",
            async: true,
            url: path,
            data: {name:value,'e':e},
            contentType: "application/json; charset=utf-8",
            dataType: "text",
            success: function (msg) {
            alert(true);
              
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('server error');
            }
        });

}

I have tried opening form with open_form then serialize it in javascript but failed too. What am I missing exactly? The CSRF data (name and value) is set correctly. Every method I saw online didnt work too. If I change the method to "get" oriented method in my controller, it works fine but it must be posted.

Any clues?
Reply
#2

This works fine to me:

Code:
<form method="post" id="some_form">
<?=form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash())?>
<input name="some_input" />
</form>

and then

Code:
$(function(){
$("body").on("submit","#some_form",function(e){
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
method: $(this).attr("method"),
data: $(this).serialize()
})
.done(function(data){
//something
})
.fail(function(){})
.always(function(){});
});
});

I hope it helps.
Reply
#3

thx Ikarius...will try and let you kno.
Reply
#4

If you have the following in your config:

PHP Code:
$config['csrf_regenerate'] = TRUE

then you need to update the CSRF token on each request. When you're using AJAX, this usually means you need to use the get_csrf_token_name() and get_csrf_hash() methods of the security library in your controller and send those values in your response to your AJAX posts, then process them in the success() or done() handler in the JavaScript, so you can send those values with your next AJAX post.

Usually when I need to do something like that, I'll setup the form something like this:

PHP Code:
<form method="post" id="some_form">
    <
input type="hidden" id="csrf" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>" /> 

This only ensures the values are correct for the first post of the form data, though, since the token name and CSRF hash are only placed in the form when the page is initially loaded. So, the JavaScript would do something like this while processing each response to an AJAX post:

Code:
$('#csrf').val(csrfHashFromResponse);
$('#csrf').attr('name', csrfTokenNameFromResponse);

The post itself also has to include the input, so the CSRF check will pass.
Reply
#5

Tks, man! Works for me.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB