1

I'm working on a project in CodeIgniter4. I'm trying to make an Ajax call to an endpoint (/adjustments/store). I'm validating the form using CodeIgniter and showing the validation errors in my view. The issue is when the first time, i submit the form, it works and shows some validation errors. But when i fill the form correclty (to get not validation errors) and resubmit it again it gives me 403 forbidden error in the console.

Ajax call

$.ajax({
    type: 'post',
    url: '/adjustments/store',
    dataType: 'html',
    data: {
      number,
      date,
      type,
      account,
      description,
      adjData,
      csrf_test_name
    },
    success: function (res) {
      if (IsJsonString(res)) {
        const response = JSON.parse(res);

        if (response.hasOwnProperty('validation_errors')) {
          const errors = response.validation_errors;
          for (err in errors) {
            $(`input[name=${ err }]`)
             .parent()
             .append(`<small class="text-danger">${ errors[err] }</small>`)
         }
      }
   }

  function IsJsonString(str) {
     try {
        JSON.parse(str);
     } catch (e) {
       return false;
     }
     return true;
 }

console.log(res);

}

CodeIgniter Controller

public function store () {
        $data = $this->request->getPost(NULL);

        // Validate
        if (! $this->validate([
            'number' => 'required',
            'date' => 'required',
            'type' => 'required',
            'adjData' => 'required',
        ]))
        {
            echo json_encode(['validation_errors' => $this->validator->getErrors()]);
            return;
        }

        echo json_encode($data);
}

Any solution to this?

MUHAMMAD Siyab
  • 436
  • 1
  • 9
  • 20
  • Can you also include the routes file where the particular route has been mentioned? – Dhaval Chheda May 12 '20 at 07:47
  • Does this answer your question? [Ajax CSRF 403 forbidden codeigniter](https://stackoverflow.com/questions/32478355/ajax-csrf-403-forbidden-codeigniter) – Don't Panic Jul 22 '20 at 00:30

1 Answers1

1

If you are resubmitting a form then you have update csrf token on every request with ajax.

Whenever validation fails pass csrf token and update it every time.

In your controller -

public function store () {
        $data = $this->request->getPost(NULL);

        // Validate
        if (! $this->validate([
            'number' => 'required',
            'date' => 'required',
            'type' => 'required',
            'adjData' => 'required',
        ]))
        {
            echo json_encode(['validation_errors' => $this->validator->getErrors(), 'csrf' => csrf_hash()]);
            return;
        }

        echo json_encode($data);
}

In you ajax -

$.ajax({
    type: 'post',
    url: '/adjustments/store',
    dataType: 'html',
    data: {
      number,
      date,
      type,
      account,
      description,
      adjData,
      csrf_test_name
    },
    success: function (res) {
      if (IsJsonString(res)) {
        const response = JSON.parse(res);
          $("input[name='csrf_test_name']").val(response ["csrf"]);
        if (response.hasOwnProperty('validation_errors')) {
          const errors = response.validation_errors;
          for (err in errors) {
            $(`input[name=${ err }]`)
             .parent()
             .append(`<small class="text-danger">${ errors[err] }</small>`)
         }
      }
   }

  function IsJsonString(str) {
     try {
        JSON.parse(str);
     } catch (e) {
       return false;
     }
     return true;
 }

So once you update csrf then it will work fine.

Thanks.

Abhishek Honrao
  • 780
  • 5
  • 28