PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 19, 2022

[FIXED] How to check existing data with jquery validation library with codeigniter 4 when csrf is set to auto?

 February 19, 2022     ajax, codeigniter, javascript, jquery, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing