I have a form that I’m trying to validate with jquery validation plugin and codeigniter 4, I have enabled csrf that set to auto generate for every request. I’m able get validation status on first request but when I try another request I get error 403, and when I set second param to json_encode() I get error 500. I want to be able to update csrf after each request on ajax call.
//My router
$routes->post('check-category', 'AdminCategory::check_category');
//my controller
//check if category name exist
public function check_category()
{
$name = $this->request->getPost('name');
$query = $this->db->table('categories')
->where(['cat_name' => $name])
->get()
->getResult();
$status = true;
if(count($query) > 1){
$status = false;
}else{
$status = true;
}
$data['csrf'] = csrf_hash();
echo json_encode($status, $data);
}
// javascript
$('#create_category').validate({
onkeyup: false,
rules: {
name: {
remote: {
url: 'check-category',
type: "post",
data:{
csrf_hash_name: function(){
return $('input[name="csrf_hash_name"]').val();
}
},
complete: function(data){
$('input[name="csrf_hash_name"]').val(data.csrf);
}
}
}
},
messages: {
name: {remote: "This category exists."}
},
submitHandler: function(form) { return false; }
});
Thanks in advance.
2
Answers
After so much struggle I finally found the solution of my problem. Now I'm able to update csrf token with the dataFilter object and get rid off error 403 during ajax call. Here is what I have done to my controller even I broked Mvc principle by getting data from db direct to the controller. I know it could not the best way for what I have done, Please correct me if any suggestion I'll appreciate. Thanks!
//my controller method
// my javascript
the structure of the php function json_encode() looks like this:
and returns:
in your controller function
check_category()
you are sending$status
, while$data
is setting an invalid flag:change
$status = true;
into$data['status'] = true
;and just echo both, status and the csrf hash