Example 1: codeigniter csrf token ajax
$csrfName = $this->security->get_csrf_token_name(); $csrfHash = $this->security->get_csrf_hash();
Example 2: csrf in codeigniter 3
<!doctype html> <html> <head> <title>How to Send AJAX request with CSRF token in CodeIgniter</title> </head> <body> <input type="text" class="txt_csrfname" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>"><br> Select Username : <select id='sel_user'> <option value='yssyogesh'>yssyogesh</option> <option value='sonarika'>sonarika</option> <option value='vishal'>vishal</option> <option value='sunil'>sunil</option> </select> <div > Username : <span id='suname'></span><br/> Name : <span id='sname'></span><br/> Email : <span id='semail'></span><br/> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type='text/javascript'> var baseURL= "<?= base_url();?>"; $(document).ready(function(){ $('#sel_user').change(function(){ var csrfName = $('.txt_csrfname').attr('name'); var csrfHash = $('.txt_csrfname').val(); var username = $(this).val(); $.ajax({ url:'<?=base_url()?>index.php/User/userDetails', method: 'post', data: {username: username,[csrfName]: csrfHash }, dataType: 'json', success: function(response){ $('.txt_csrfname').val(response.token); $('#suname,#sname,#semail').text(''); $(response[0]).each(function(key,value){ var uname = value.username; var name = value.name; var email = value.email; $('#suname').text(uname); $('#sname').text(name); $('#semail').text(email); }); } }); }); }); </script> </body> </html>
Comments
Post a Comment