Skip to content Skip to sidebar Skip to footer

Ajax Request With Codeigniter 403 (forbidden)

I'm trying to send an value with Ajax to Controller file in Codeigniter but without success.I have searched for that problem and i now this question is made many times here,but sti

Solution 1:

Add this code in your footer view before including JS file

<?php$CI =& get_instance(); ?><script>var csrf_name = '<?phpecho$CI->security->get_csrf_token_name(); ?>';
    var csrf_hash = '<?phpecho$CI->security->get_csrf_hash(); ?>';
</script>

and just call these variables anywhere you need like this

data:{
     csrf_name : csrf_hash,
     'message': message
},

Solution 2:

I'm afraid you can't use PHP tags in JavaScript files, as you've mentioned you have a JS file.

You must run your PHP codes in .php files.

Perhaps you can decouple your submitSend() function a bit and make it more modular by extracting the PHP tags as well as $('#sms').val(). These can be passed to the function as parameters from where you call it (.php files).

Solution 3:

Most probably its because of the CSRF token try disable csrf and check if its due to csrf then do whitelist the specific function in csrf config

Solution 4:

This work for me.

/app/Config/Security.php

/**
     * --------------------------------------------------------------------------
     * CSRF Token Name
     * --------------------------------------------------------------------------
     *
     * Token name for Cross Site Request Forgery protection cookie.
     *
     * @var string
     */public$tokenName = 'csrf_token_name';

Inside my form

<inputtype="hidden"name="<?= csrf_token() ?>"value="<?= csrf_hash() ?>" />

in the script.js

var tokenHash=jQuery("input[name=csrf_token_name]").val();
$.ajax({
  method: "POST",
  url: "/somecontroller",
  data: { name: "John", location: "Boston" },
beforeSend: function (xhr) 
        {       
        xhr.setRequestHeader('X-CSRF-Token' , tokenHash);       
        },
})
  .done(function( msg ) {
    console.log( "Data Saved: " + msg );
  });
    

Solution 5:

You can't use php tag in js file

url: "<?phpecho base_url();?>/mychat/send", //this line in js file is wrong

You only use php tag in script tag in .php file like this

<script>// ... some code here url: "<?phpecho base_url();?>/mychat/send",
 // ... some code here
</script>

Or add this line in header html

<script>varBASE_URL = '<?phpecho base_url(); ?>';
</script>

and use it in js file

....
url: BASE_URL+"mychat/send",
....

Post a Comment for "Ajax Request With Codeigniter 403 (forbidden)"