Welcome Guest, Not a member yet? Register   Sign In
CSRF Token AJAX
#1

Hi

I have an AJAX FORM that using form_open() fucntion.

If $config['csrf_protection'] = TRUE, the FORM doesnt work.
If $config['csrf_protection'] = FALSE, the FORM works fine.

Is it posibble to keep using CSRF Token in AJAX FORM?
Reply
#2

Yes, it's possible. You have to send new csrf token in every response to the website and handle it with jquery/js
Reply
#3

This will explain it better for you.

AJAX + CSRF Protection in Codeigniter
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4

Thanks guys
Reply
#5

(This post was last modified: 03-22-2018, 07:52 PM by buzztomi.)

Hello guys

It looks like my ajax form stil not working well.
Here are the code

The View code

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#loginForm').submit(function(event) {
var formData = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'password' : $('input[name=password]').val(),
'email' : $('input[name=email]').val()
};
$.ajax( {
type : 'POST',
url :'<?=base_url().'user/login',
data : formData,
dataType : 'json',
encode : true,
success:function(data) {
if ( ! data.success) {
alert("Incorect login data");
}else {
alert("Correct login data");
}

},
error: function (xhr, ajaxOptions, thrownError) {
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
})
event.preventDefault();
});
});
</script>
</head>
<body>

<?php
echo form_open('user/login','id="loginForm"');
echo form_input(['type' => 'email','name' => 'email','placeholder' => 'Email','required'=>'required']);
echo form_input(['type' => 'password','name' => 'password','placeholder' => 'Password','required'=>'required']);
echo '<button type="submit" form="loginForm">Login</button>';
echo form_close();
?>
</body>
</html>



The Controller code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
}


public function index()
{
$this->load->helper('form');
$this->load->view('dashboard/login');
}

public function login() {
$noError = array();
$email=strtolower($this->input->post('email', TRUE));
$password=$this->input->post('password', TRUE);
if($email=='[email protected]' && $password=='12345'){
$noError['success'] = TRUE;
}
else{
$noError['success'] = FALSE;
}
echo json_encode($noError);
}
}


The problem is , when the button click more than once, the form bocome not working

You can see the video here
https://www.youtube.com/watch?v=sjSYRTVEtU0

What seems to be the problem?
Reply
#6

Hi, yes, that would be the correct outcome if you have $config['csrf_regenerate'] = TRUE, which looks like you do.

The CI guide: "Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc)."  - https://www.codeigniter.com/user_guide/l...rgery-csrf

As Kmycic states, you need to return a new CSRF token in your ajax response and then have JS update your form field if you wish to submit the form again.

In addition to that, you are using the form_open function which will add your CSRF token to the form, there is no need to add it directly to the java script function.  I would look at the ajax serialize function which will include the hidden CSRF token when the form is submitted.
Reply
#7

This is my solution
PHP Code:
var csrf_token '<?php echo $this->security->get_csrf_hash(); ?>';
$.
ajax({
 
urlyoururl,
data: {
 
post_title : $("#post_title").val(),
 
post_content : $("#post_content").val(),
 
csrf_test_name csrf_token
 
},
type'POST',
success: function (data) {
 
//your success action
}
}) 
Reply
#8

Your Ajax url is wrong for one.

PHP Code:
url :'<?=base_url().'user/login',

// Should be
url :"<?=base_url('
user/login); ?>", 

I do this in the head of my html document for the url's.

Code:
    <!-- Pass base_url() and site_url() to jQuery JavaScript -->
    <script>
        var baseUrl = "<?php echo base_url(); ?>";
        var siteUrl = "<?php echo site_url(); ?>";
    </script>

Then in jQuery you can use baseUrl or siteUrl for url's.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB