Welcome Guest, Not a member yet? Register   Sign In
How to check existing data with jquery validation library with codeigniter 4 csrf?
#1

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.

PHP Code:
//My router

  $routes->post('check-category''Admin\Category::check_category');

//my controller

    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);
    
Code:
// 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.
Reply
#2

(This post was last modified: 01-15-2021, 08:05 PM by iRedds.)

God, how did you get to this age?  Big Grin

I hope this is just a sample code. But if you are using database queries in the controller this is a bad practice and a violation of the MVC pattern.
Use the model to work with the database.

1. Use ->countAllResults() instead of ->get()->getResult();
2. When you make a POST request with CSRF enabled, the hash changes. For each subsequent request, you must use a new hash. Since you don't, you will receive an HTTP 403 error.
3. Check out the manual for the json_encode function. And you will understand what you are doing wrong.(Hello HTTP 500 error)
https://www.php.net/manual/en/function.json-encode.php

And if you fully use the framework, then it is better to read the documentation on this topic
https://codeigniter.com/user_guide/outgo...the-output
Reply
#3

(01-15-2021, 08:04 PM)iRedds Wrote: God, how did you get to this age?  Big Grin

I hope this is just a sample code. But if you are using database queries in the controller this is a bad practice and a violation of the MVC pattern.
Use the model to work with the database.

1. Use ->countAllResults() instead of ->get()->getResult();
2. When you make a POST request with CSRF enabled, the hash changes. For each subsequent request, you must use a new hash. Since you don't, you will receive an HTTP 403 error.
3. Check out the manual for the json_encode function. And you will understand what you are doing wrong.(Hello HTTP 500 error)
https://www.php.net/manual/en/function.json-encode.php

And if you fully use the framework, then it is better to read the documentation on this topic
https://codeigniter.com/user_guide/outgo...the-output
 Thank you very much. I corrected  with your suggestion. but my problem now is  how I can update csrf on jqery remote object " remote:{ data:{} } "?
Reply
#4

(01-16-2021, 12:39 AM)onebuyu Wrote:  Thank you very much. I corrected  with your suggestion. but my problem now is  how I can update csrf on jqery remote object " remote:{ data:{} } "?

I don't understand the essence of the problem.
I don't know how the library works, but I assume that you already have some code that overwrites the csrf hash.

Code:
complete: function(data){
   $('input[name="csrf_hash_name"]').val(data.csrf);
}
and the value of the csrf_hash_name key in the "data" object is computed on every request.

Just send data
PHP Code:
return $this->response->setJSON([
    'status' => ! (bool) $count// convert number to boolean and invert ( 0 = true; > 0 = false)
    'csrf' => csrf_hash()
]); 


Receiving data
Code:
complete: function(data){
    $('input[name="csrf_hash_name"]').val(data.csrf);
    return data.status;
}
Reply




Theme © iAndrew 2016 - Forum software by © MyBB