'Ajax error 403 Forbidden CodeIgniter
I have two links on my html page :
<a id="1" onclick="like(this.id)">first</a>
<a id="2" onclick="like(this.id)">Second</a>
My JS is the following :
function like (id) {
$.ajax({
type:'POST',
data: {
func:
'getNewLocations',
'<?php echo $this->security->get_csrf_token_name(); ?>':
'<?php echo $this->security->get_csrf_hash(); ?>',
message:id
},
url:'<?php echo base_url();?>index.php/Category/like',
success: function(result, statut) {
if (result == 'add') {
//do something
}
else if (result == 'remove') {
//do something
}
}
});
}
And the php method is the following (just for the example):
public function like() {
echo 'add';
}
When I click at first on the link 1, the ajax request works fine, the server answers 'add'. But when I click on the link 2, I have a 403 error. Even more surprising, when I click at fisrt on the link 2, it works but then the link 1 doesn't. I work with codeIgniter.
Any idea of why and how solve it ? Thanks
Solution 1:[1]
After the first submit the csrf token is no longer valid, you have two options.
You can either set the following in config.php
$config['csrf_regenerate'] = FALSE;
or update the csrf token on the page.
Solution 2:[2]
For Codeigniter 4
First, go to app/Config/Security.php
change
public $regenerate = true;
To
public $regenerate = false;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | M_Khater |
