skip to Main Content

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


  1. Chosen as BEST ANSWER

    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;
            }
          });
    

  2. the structure of the php function json_encode() looks like this:

    json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|false
    

    and returns:

    a string containing the JSON representation of the supplied value.

    in your controller function check_category() you are sending $status, while $data is setting an invalid flag:

    echo json_encode($status, $data);  // wrong
    

    change $status = true; into $data['status'] = true;

    and just echo both, status and the csrf hash

    echo json_encode($data);  // correct
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search