Issue
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', 'Admin\Category::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.
Solution
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
public function check_category()
{
$name = $this->request->getPost('name');
$query = $this->db->table('categories')->where(['cat_name' => $name])->countAllResults();
$valid = true;
if($query > 0){
$valid = false;
}else{
$valid = true;
}
$csrf = csrf_hash();
return $this->response->setJSON(['valid'=>$valid, 'csrf'=>$csrf]);
}
// my javascript
$('#create_category').validate({
onkeyup: false,
rules: {
name: {
required: true,
remote: {
url: 'check-category',
type: 'post',
dataType:'json',
dataFilter: function(data){
let obj = eval('('+data+')');
$('input[name="csrf_hash_name"]').val(obj.csrf);
return obj.valid;
},
data:{ csrf_hash_name: function(){ return $('input[name="csrf_hash_name"]').val(); } }
}
}
},
messages: {
name: {
required: "Enter a Category.",
remote: "{0} This category exists."
}
},
submitHandler: function(form) {
return false;
}
});
Answered By - ven
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.