How to include CSRF from Codeigniter in ajax data

I try to transfer some data to my controller, but I get 500 errors. After some research, I found that this is because the CSRF token is not being sent.

It seems I need to include this along with the data: <?php echo $this->security->get_csrf_token_name(); ?>:"<?php echo $this->security->get_csrf_hash(); ?>"

My JS is pretty weak, so I'm a bit confused about how to change this to include the above.

<script type="text/javascript"> 
$(document).ready(function() {
    $("#order").sortable({
        update : function (event, ui) {
            order = $('#order').sortable('serialize');
            $.ajax({
                url: "<?=base_url().'admin/category/update_order'?>",
                type: "POST",
                data: order,
                success: function(response){
                    console.log(response);
                }
            });
        }
    });
}
);
</script>
+5
source share
6 answers

The token must be passed in the argument data $.ajax.

This should work, but see my notes below.

order['<?php echo $this->security->get_csrf_token_name(); ?>'] = '<?php echo $this->security->get_csrf_hash(); ?>';

. PHP javascript, javascript ( , , ).

<form> html, .

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>" />

.

URL- action. script , URL- 2.

<form id="order" method="post" action="<?=base_url()?>admin/category/update_order">

$.ajax - url: $('#order').attr('action'),, , #order .

+3

CI csrf cookie, :

var csrf = $.cookie('csrf_cookie_name');

, jQuery cookie. , jquery.

+2

, CSRF . jQuery $.extend , , CSRF, :

$.extend(alerts, {
'<?php echo $this->security->get_csrf_token_name(); ?>' :
'<?php echo $this->security->get_csrf_hash(); ?>' });
+1

. Auth.php, - csrf JSON. , javascript, ajax, csrf creds , - submit.

// Auth.php

public function get_csrf()
{
    $csrf['csrf_name'] = $this->security->get_csrf_token_name();
    $csrf['csrf_token'] = $this->security->get_csrf_hash();

    echo json_encode($csrf);
}

//myFunction()

<script type="text/javascript">
function myFunction() {

    // first ajax call to grab the csrf name and token
    // from our get_csrf() function in Auth.php
    $.ajax({
        type: "GET",
        dataType: 'json',
        url: "https://<your_domain>.com/auth/get_csrf", //replace with your domain
        success: function (data) {

            // assign csrf name and token to variables
            csrf_name = data.csrf_name;
            csrf_token = data.csrf_token;

            // assign field1 and field2 field values to variables
            var form_field1 = document.getElementById('field1').value;
            var form_field2 = document.getElementById('field2').value;

            // insert csrf creds into form
            $('#csrftoken').attr('name', csrf_name);
            $('#csrftoken').val(csrf_token);

            // second ajax call -- this is our form handler
            $.ajax({
                type: "POST",
                url: "https://<your_domain>.com/<your_controller>/<your_function>", //replace with your domain/controller/function
                data: {
                    // ES6 computed property keys are great...
                    [csrf_name] : csrf_token,
                    "field1" : form_field1,
                    "field2" : form_field2
                      },
                success: function(data) {

                    // handle the return from your form submit
                    if (data == "ok") {
                        console.log("Success!");
                        $("#infoMessage").html("<p>Success</p>").fadeIn(300);

                    } else {

                        console.log("Oops!");
                        $("#infoMessage").html("<p>Oops!</p>");

                    }

                }
            });

        }
    });

}
</script>

//html

<div id="infoMessage"></div>

<form method="post" accept-charset="utf-8">

    <input type="hidden" id="csrftoken" name="" value="" />

    <label for="field1">Field 1:</label> <br />
    <input type="text" name="field1" id="field1"  />

    <label for="field2">Field 2:</label> <br />
    <input type="text" name="field2" id="field2"  />

    <input type="button" name="submit" value="SUBMIT" onclick="myFunction()" />

</form>
+1
source

I am expanding form_helperhow MY_form_helper.phpto serve csrf tokens for my own form generation code - you could use something similar:

    function secure_form() {
        $CI =& get_instance();
        return '<input type="hidden" name='.$CI->security->get_csrf_token_name().' value='.$CI->security->get_csrf_hash().'>';
    }
0
source

another solution is to use .serialize ():

$.post("user/save", $('#frmUser').serialize(),function(html){
        $("#results").html(html);
});

which will find the hidden field in which the CSRF data is stored.

0
source

All Articles