0

I want to send CSRF token In Codeigniter via JS File Using Ajax.Here is my code

// main.js (JS File)
 $("button").on("click",function(){
    var csrf_name = $("#CSRF").attr("name");
    var csrf_token = $("#CSRF").val();
        $.ajax({
            url: "Test/demo",
            type: "POST",
            data:{
                csrf_name: csrf_token ,
            },
            success: function(data)
            {
                alert(data);
            }

        });
});

It is Test Controller:

class Test extends CI_Controller
{
     public function demo()
     {
        echo "Success";
     }
}
EzLo
  • 13,780
  • 10
  • 33
  • 38

1 Answers1

0

This will send ajax token on every request. You should put it in your header file after jquery is loaded.

<script>
                var token = {}; // forgot this
                token['<?php echo $this->security->get_csrf_token_name() ?>'] = '<?php echo $this->security->get_csrf_hash() ?>';
                    jQuery.ajaxSetup({
                        data: token,
                        type: 'POST',
                        error: function (jqXHR, textStatus, errorThrown) {
                            if (jqXHR.status == 404) {
                                alert('AJAX page not found.');
                            } else {
                                console.error('AJAX Error: ' + textStatus + ': ' + errorThrown);
                            }
                        }
                    });
</script>
Alex
  • 9,215
  • 8
  • 39
  • 82
  • where i Put this code ? token['security->get_csrf_token_name() ?>'] = 'security->get_csrf_hash() ?>'; – A.Developer May 06 '19 at 07:07
  • where do you currently load jquery? header or footer? – Alex May 06 '19 at 07:12
  • my js file load in footer section – A.Developer May 06 '19 at 07:14
  • ok, so in footer view, underneath where you load jquery, add the above script section. now with all ajax requests the token (csrf) will be sent along with them so you don't have to manually do it in every request. – Alex May 06 '19 at 07:15
  • and jQuery.ajaxSetup...... this code i puted in js File – A.Developer May 06 '19 at 07:16
  • you could but i would recommend keeping it in the view. the token part absolutely has to be in a view as it contains php code that would work in a js file. if you do put it in js file you would have to include that file before other js files and after jquery is loaded for it to work. – Alex May 06 '19 at 07:17
  • Bro, Its not working for me.Have u an example. – A.Developer May 06 '19 at 07:27
  • https://jsfiddle.net/41qcybp0/ ... please note i've updated above code, forgot to declare token. https://imgur.com/a/8mNcpTG – Alex May 06 '19 at 07:43