Ajax Request With Codeigniter 403 (forbidden)
Solution 1:
Add this code in your footer view before including JS file
<?php $CI =& get_instance(); ?>
<script>
var csrf_name = '<?php echo $CI->security->get_csrf_token_name(); ?>';
var csrf_hash = '<?php echo $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
<input type="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: "<?php echo 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: "<?php echo base_url();?>/mychat/send",
// ... some code here
</script>
Or add this line in header html
<script>
var BASE_URL = '<?php echo base_url(); ?>';
</script>
and use it in js file
....
url: BASE_URL+"mychat/send",
....
Post a Comment for "Ajax Request With Codeigniter 403 (forbidden)"