0

I have an ajax function in jquery caling a cakephp4 function. The function doesnt work as it is giving a 403 forbidden error. The error is about headers but i cant find what I need to fix this exactly.

This code runs and it does get the var (alert verifies this). Nothing works ? jquery ///

var freeassessmentid = "<?=$testid?>";
  
  $.ajax({
            url: "/freeassessments/freeasssesmenFinaltResult", //path is correct and it can be tested on its own
            method: "POST",
            dataType: "html",
            data: { freeassessmentid:freeassessmentid  },
            success: function(response) {
                //console.log(response);
                   
                  $('#display-area').append(response);  //no output
               }
               
               
               
            });

public function freeasssesmenFinaltResult($freeassessmentid=0)
 {
//debug('test');
 $html .= '<li class="listyle" style="height: auto;">hi<br/></li>';
          $html .= '</ul>';
//no output

 //https://stackoverflow.com/questions/36666256/jquery-ajax-call-results-in-error-status-403
atown99
  • 109
  • 12

2 Answers2

0

The Ajax url should be:

url: "/freeassessments/freeasssesmen-finalt-result",

Use the kebab case for actions/methods in urls and the camel case for them in the controllers

0

You have to pass CSRF token in header during ajax call.

You can get CSRF token in many ways.

One of the simplest way is:

You can add bellow code to your head tag of parent layout or inside any of your template file.

<?php echo $this->Html->meta("csrfToken", $this->request->getAttribute("csrfToken")); ?>

At the time of ajax call you will have to get this csrf token and pass it to the ajax header. Here is the example:

var token = $("meta[name='csrfToken']").attr("content");
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': token
    }
});
$.ajax({
    url: "path/to/controller/method", 
    method: "POST",
    data: { pram1:val },
    success: function(response) {
        //console.log(response);   
    }        
});

I hope it may help :)

sanjay verma
  • 257
  • 1
  • 8