call of javascript function to external url always blocked by cors


I created a javascript function that have to be called every time someone clicks a button. This is the code present on file /wp-includes/js/utm.js:

function event_click() {
    document.getElementById("cf_submit-site-aa7bccxxxx").addEventListener("click", prepareData2DB);

function prepareData2DB() {
        // prepare body to send request 
        visitant = ...;

function send2DB(visitant) {
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log('response:' + this.response);
    };"POST", "", true);
    xmlHttp.setRequestHeader('Content-type', 'application/json');
    xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*');
    xmlHttp.setRequestHeader('Access-Control-Allow-Methods', 'POST');
    xmlHttp.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');

This file is imported on footer.php:

<script type='text/javascript' src="/wp-includes/js/utm.js"></script>

When the button is clicked and the function triggered, I got this error on console:

Access to XMLHttpRequest at ‘
from origin ‘‘ has been blocked by CORS
policy: Response to preflight request doesn’t pass access control
check: No ‘Access-Control-Allow-Origin’ header is present on the
requested resource

I already added this code on functions.php:

function add_cors_http_header(){
    header("Access-Control-Allow-Origin: *");

And using both and on call with the xyz url, I got:


Last, I used this plugin, but neither worked.

I don’t know what else I can do to transpass this error.

, mhery 4 years 2020-03-25T12:50:56-05:00 0 Answers 108 views 0

Leave an answer