CodeIgniter Forums
XMLHttpRequest error and isAjax not work - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: XMLHttpRequest error and isAjax not work (/thread-80008.html)



XMLHttpRequest error and isAjax not work - Secux - 09-01-2021

i am trying to make the following request with ajax but i get an error - 
XMLHttpRequest cannot load https://api.domain.com/view?id=1&csrf_name=fbadd9981aa3c2850b03b8eb52aa75ca&_=1630524468477 due to access control checks.

my script:
Code:
$.ajax({
    url:'https://api.domain.com/view',
    method: 'get',
data: {'id':'<?= session()->get('id') ?>','<?= csrf_token() ?>':'<?= csrf_hash() ?>'},
headers: {'X-Requested-With': 'XMLHttpRequest'},
dataType: "json",
cache: false,
success: function (data) {

url site: https://my.domain.com
controller:
PHP Code:
public function view() {

if (
$this->request->isAJAX())        

 
/* my code */

}


i also think the isAjax check doesn't work either


RE: XMLHttpRequest error and isAjax not work - iRedds - 09-02-2021

Read about CORS and Access-Control-Allow-Origin header


RE: XMLHttpRequest error and isAjax not work - Secux - 09-03-2021

I tried to add a header but it doesn't work.
there may be some special way to add a header in codeigniter 4?

Help me


RE: XMLHttpRequest error and isAjax not work - InsiteFX - 09-03-2021

This is how I do it in public where index.php is .htaccess file add this.

Code:
## .htaccess Control For CORS Configuration

# Add Font Awesome Font Types
AddType application/vnd.ms-fontobject .eot
AddType application/x-font-ttf        .ttf
AddType application/x-font-opentype  .otf
AddType application/font-woff        .woff
AddType application/font-woff2        .woff2

<IfModule mod_headers.c>
    <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|svg|svgz|jpg|png|ico|font.css|css|js)$">
        ## un-remark this one for all access and remark out the one below it
        #Header set Access-Control-Allow-Origin "*"
        ## Change this to your local host url. and https or http
        Header add Access-Control-Allow-Origin: "https://yoursite.com"
        Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
        Header add Access-Control-Allow-Headers: "Upgrade-Insecure-Requests"
    </FilesMatch>
</IfModule>

# Remove index.php from URL
RewriteCond %{HTTP:X-Requested-With}    !^XMLHttpRequest$
RewriteCond %{THE_REQUEST}              ^[^/]*/index\.php [NC]
RewriteRule ^index\.php(.*)$            $1 [R=301,NS,L]

That should work for you.