CORS policy: No 'Access-Control-Allow-Origin' error in yii2

Hi,
I am using yii2 basic application template. I have a VPS server with hostgator and I have created subdomain ifsoft under my primary domain. I have transfered my basic folder through File Zilla into public_html/ifsoft. I have also changed the document root of this subdomain to public_html/ifsoft/basic/web
Everything works fine. I can accessmy admin panel, but on dashboard/index, the graph is not displayed at all whereas on localhost and on primary domain it works very fine. When I inspect the code the error is as below:

Access to XMLHttpRequest been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

So in my views/dashboard/ I have,

  1. index.php
  2. data.php
  3. app.js

1 . Here, index.php is the dashboard page and on this page I have a code as below:

<div class="box box-success">
            <div class="box-body">
              <div class="chart">
                  
					<canvas id="barChart" width="50" height="20"></canvas>
			  </div>
		    </div>
		</div>
  1. In data.php I have written My SQL query which returns total no of groups each FieldOfficer has.
<?php
header('Content-Type: application/json');
$servername = "";
$username = "";
$password = "";
$dbname = "";

$conn = new mysqli($servername, $username, $password,$dbname);

if ($conn->connect_error) {
   
} 

$sql = "SELECT CONCAT(employee.FirstName,' ',employee.LastName) as FullName, count(*) as TotalGroups from groupdetails, employee WHERE groupdetails.EmpId=employee.EmpId group by groupdetails.EmpId";

$result = $conn->query($sql);

if ($result!=null) {
  
   $data = array();
	foreach ($result as $row) {
	$data[] = $row;
	}
} 
$conn->close();

print json_encode($data);

In above data.php I have mentioned all my database credentials properly. It works

  1. Now in app.js I have foll code,
$(document).ready(function(){
	$.ajax({
		url: "data.php",
		method: "GET",
			dataType: "json",
		success: function(data) {
			console.log(data);
			var emp = [];
			var groups = [];

			for(var i in data) {
				emp.push(" " +data[i].FirstName);
				groups.push(data[i].TotalGroups);
			}

			var chartdata = {
				labels: emp,
				datasets : [
					{
						label: 'SHG Groups',
						backgroundColor: 'rgba(200, 200, 200, 200)',
						borderColor: 'rgba(200, 200, 200, 0.75)',
						hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
						hoverBorderColor: 'rgba(200, 200, 200, 1)',
						data: groups
					}
				]
			};

			var ctx = document.getElementById("barChart");

			var barGraph = new Chart(ctx, {
				type: 'bar',
				data: chartdata
			});
		},
		error: function(data) {
			console.log(data);
		}
	});
});

How to resolve this?

A post was merged into an existing topic: How to start the yii application on subdomain?