Jump to content

Pass the PHP vaiable to js file using ajax script


Go to solution Solved by Senthilkumar,

Recommended Posts

Dear Team,

I am using Canvas grap on my PHP project. I am using PHP query on the same page and defining the as a variable on a script and passing the script to another js file.

My code is 

$previous_month = date('Y-m', strtotime(date('Y-m') . " -1 month"));
$Year = date('Y');


$Mc = "SELECT Region,  McTotal, McAssigned FROM
			( SELECT count(a.BranchCode) as McTotal, c.regnName as Region  FROM sbms.machinemaster as a
			inner join sbms.branch as b on b.branchcode = a.BranchCode
			inner join sbms.region as c on c.regnID = b.regnID
			WHERE  a.MachineStatus='A' AND c.regnID !='5'  group by c.regnID ) total

			LEFT JOIN (Select count(a.RowID) as McAssigned , c.regnName as Region FROM sbms.production as a
			inner join sbms.branch as b on b.branchID = a.Branch
			inner join sbms.region as c on c.regnID = b.regnID WHERE a.Month = '$previous_month'
			group by c.regnID order by c.regnID ASC ) assigned USING (Region)";
$Mcresult = mysqli_query($conn, $Mc);

while ($Mcrow = mysqli_fetch_array($Mcresult)) {
	$McRegion[] = $Mcrow['Region'];
	$McTotal[] = $Mcrow['McTotal'];
	$McAssigned[] = $Mcrow['McAssigned'];
}

$MachineTotal = json_encode($McAssigned);
$MachineAssigned = json_encode($McTotal);
$MachineRegion = json_encode($McRegion);


<div class="col-12 col-md-6 col-lg-6 col-xl-6">
				<div class="card">
					<div class="card-body">
						<div class="chart-title">
							<div class="float-left">
								<h5>Active Machine vs Production Data Collected for <?PHP echo $previous_month1; ?></h5>
							</div>
							<div class="float-right">
								<a href="Machine_Report.php" type="button" class="btn btn-default subs-btn">View Details</a>
							</div>
						</div>
						<canvas id="MachineBarGraph"></canvas>
					</div>
				</div>
</div>


<script type="text/javascript">
	var MachineTotal = <?php echo $MachineTotal ?>;
	var MachineAssigned = <?php echo $MachineAssigned ?>;
	var MachineRegion = <?php echo $MachineRegion ?>;	
</script>

<script src="../assets/js/DashboardGraph.js"></script>

DashboardGraph.js




$(document).ready(function () {

    // Active Equipment Vs Data Collected

    var barChartData = {
        labels: MachineRegion,
        datasets: [{

            label: 'Active Machine',
            backgroundColor: 'rgba(0, 158, 251, 0.5)',
            borderColor: 'rgba(0, 158, 251, 1)',
            borderWidth: 1,
            data: MachineAssigned
        }, {
            label: 'Data Collected',
            backgroundColor: 'rgba(255, 188, 53, 0.5)',
            borderColor: 'rgba(255, 188, 53, 1)',
            borderWidth: 1,
            data: MachineTotal
        }]
    };

    var myoption = {
        responsive: true,
        tooltips: {
            enabled: true,
        },
        hover: {
            animationDuration: 1
        },
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                }
            }],
            xAxes: [{
                ticks: {
                    autoSkip: false
                }
            }]
        },
        animation: {
            duration: 1,
            onComplete: function () {
                var chartInstance = this.chart,
                    ctx = chartInstance.ctx;
                ctx.textAlign = 'center';
                ctx.fillStyle = "rgba(0, 0, 0, 1)";
                ctx.textBaseline = 'bottom';

                this.data.datasets.forEach(function (dataset, i) {
                    var meta = chartInstance.controller.getDatasetMeta(i);
                    meta.data.forEach(function (bar, index) {
                        var data = dataset.data[index];
                        ctx.fillText(data, bar._model.x, bar._model.y + 1);

                    });
                });
            }
        },
        maintainAspectRatio: true
    };

    var ctx = document.getElementById('MachineBarGraph').getContext('2d');
    window.myBar = new Chart(ctx, {
        type: 'bar',
        data: barChartData,
        options: myoption,
    });


    
});

 

I want to apply a filter to this query. For that, I want to use the Ajax method. so that if I change my filter, the graph will change accordingly.

I don't know how to do this. Can any one please help me how to do this

What part are you having a problem with?

Is it the Javascript? Can you change your Javascript so that the graph can update when one of those variables changes? Make a function to do this, make its arguments be those three values, then call that function when the page loads.

Is it the PHP? Can you change the code so that it filters in the way you want, getting whatever values it needs to do so from $_POST?

Below is the script 

<script type="text/javascript">
	$(document).ready(function () {
		ProductionFilter();
	});

	$(document).on('change', '.filter', function () {
		ProductionFilter();
	});


		function ProductionFilter() {
			var Month = document.getElementById("Month").value;
			var Region = document.getElementById("Region").value;
			var Branch = document.getElementById("Branch").value;
			var Equipment = document.getElementById("Equipment").value;
			$.ajax({
				url: 'Customer_Graph_Filter.php',
				type: 'POST',
				data: 'Month=' + Month + '&Region=' + Region + '&Branch=' + Branch + '&Equipment=' + Equipment,
				dataType: 'JSON',
				success: function (chart_values) {
					console.log(chart_values);
					// Total Customer Vs Data Collected

					var barChartData = {
						labels: CustomerRegion,
						datasets: [{


							label: 'Total Customers',
							backgroundColor: 'rgba(0, 158, 251, 0.5)',
							borderColor: 'rgba(0, 158, 251, 1)',
							borderWidth: 1,
							data: CustomerAssigned
						}, {
							label: 'Data Collected',
							backgroundColor: 'rgba(255, 188, 53, 0.5)',
							borderColor: 'rgba(255, 188, 53, 1)',
							borderWidth: 1,
							data: CustomerTotal
						}]
					};

					var myoption = {
						responsive: true,
						tooltips: {
							enabled: true
						},
						hover: {
							animationDuration: 1
						},
						scales: {
							yAxes: [{
								ticks: {
									beginAtZero: true,
								}
							}],
							xAxes: [{
								ticks: {
									autoSkip: false
								}
							}]
						},
						animation: {
							duration: 1,
							onComplete: function () {
								var chartInstance = this.chart,
									ctx = chartInstance.ctx;
								ctx.textAlign = 'center';
								ctx.fillStyle = "rgba(0, 0, 0, 1)";
								ctx.textBaseline = 'bottom';

								this.data.datasets.forEach(function (dataset, i) {
									var meta = chartInstance.controller.getDatasetMeta(i);
									meta.data.forEach(function (bar, index) {
										var data = dataset.data[index];
										ctx.fillText(data, bar._model.x, bar._model.y + 1);

									});
								});
							}
						},
						maintainAspectRatio: true
					};

					var ctx = document.getElementById('CustomerBarGraph').getContext('2d');
					window.myBar = new Chart(ctx, {
						type: 'bar',
						data: barChartData,
						options: myoption,
					});
				}
			});
		}

</script>

Customer_Graph_Filter.php

<?PHP

include("../connection.php");

$Month = $_POST["Month"];
$Region = $_POST["Region"];
$Equipment = $_POST["Equipment"];

if ($Equipment == '') {
	$EquipCondition = '';
} else {
	$EquipCondition = 'AND ModelGroup = ' .$Equipment.'';
}


if ($Region == '') {

	$Mc = "SELECT Region,  CuTotal, CuAssigned FROM
			( SELECT count(distinct a.CustomerID) as CuTotal, c.regnName as Region  FROM sbms.machinemaster as a 
inner join sbms.branch as b on b.branchcode = a.BranchCode 
inner join sbms.region as c on c.regnID = b.regnID
WHERE a.MachineStatus = 'A' $EquipCondition AND c.regnID !='5' group by c.regnID) total

			LEFT JOIN (Select count(a.RowID) as CuAssigned , c.regnName as Region FROM sbms.customerdata as a
			inner join sbms.branch as b on b.branchID = a.Branch
			inner join sbms.region as c on c.regnID = b.regnID 
			inner join sbms.machinemaster as d on d.id = a.RowID
			WHERE a.Month = '$Month' $EquipCondition and d.MachineStatus='A' AND a.VisitType !='No Due' AND a.Status ='1'
			group by c.regnID order by c.regnID ASC ) assigned USING (Region)";
	$Mcresult = mysqli_query($conn, $Mc);

	$McNoRow = mysqli_num_rows($Mcresult);

	$return_arr[] = array('Region', 'Active Customer', 'Visited');
	while ($Mcrow = mysqli_fetch_array($Mcresult)) {
		$McRegion = $Mcrow['Region'];
		$McTotal = $Mcrow['CuTotal'];
		$McAssigned = $Mcrow['CuAssigned'];

		$return_arr[] = array(
			$McRegion,
			$McTotal,
			$McAssigned,
		);
	}

	echo json_encode($return_arr, JSON_NUMERIC_CHECK);

}

if ($Region !== '') {
	$Mc = "SELECT Branch,  McTotal, McAssigned FROM
			( SELECT count(distinct a.CustomerID) as McTotal, b.branchName as Branch  FROM sbms.machinemaster as a 
				inner join sbms.branch as b on b.branchcode = a.BranchCode 
				inner join sbms.region as c on c.regnID = b.regnID
				WHERE a.MachineStatus = 'A' $EquipCondition  AND c.regnID ='$Region'  group by b.branchcode) total

			LEFT JOIN (Select count(a.RowID) as McAssigned , b.branchName as Branch FROM sbms.customerdata as a
			inner join sbms.branch as b on b.branchID = a.Branch
			inner join sbms.region as c on c.regnID = b.regnID 
			inner join sbms.machinemaster as d on d.id = a.RowID
			WHERE a.Month = '$Month' $EquipCondition and d.MachineStatus='A' AND b.regnID = '$Region' AND a.VisitType !='No Due' AND a.Status ='1'
			group by b.branchID ) assigned USING (Branch)";
	$Mcresult = mysqli_query($conn, $Mc);

	$McNoRow = mysqli_num_rows($Mcresult);

	$return_arr[] = array('Region', 'Active Machine', 'Procuction Data Collected');
	while ($Mcrow = mysqli_fetch_array($Mcresult)) {
		$McRegion = $Mcrow['Branch'];
		$McTotal = $Mcrow['McTotal'];
		$McAssigned = $Mcrow['McAssigned'];

		$return_arr[] = array(
			$McRegion,
			$McTotal,
			$McAssigned,
		);
	}

	echo json_encode($return_arr, JSON_NUMERIC_CHECK);
}




?>

The response I am getting 

[
  [
    "Region",
    "Active Customer",
    "Visited"
  ],
  [
    "EAST",
    1843,
    289
  ],
  [
    "WEST",
    3000,
    402
  ],
  [
    "NORTH",
    1733,
    32
  ],
  [
    "SOUTH",
    2568,
    285
  ]
]

I don't know how to append this response to graph

That response doesn't look like the data you need. In the earlier code, you had three arrays: one of Region, one of McTotal, and one of McAssigned. Now you have one single array with all of the Branch (not Region?), McTotal, and McAssigned values.

If you make your PHP return the three arrays separately from each other (such as in an object) then your Javascript can take the three arrays and use them with the graph.

  • Solution

I changed the code as per your instructions. Now it is working.

<?PHP

include("../connection.php");

$Month = $_POST["Month"];
$Region = $_POST["Region"];
$Equipment = $_POST["Equipment"];

if ($Equipment == '') {
	$EquipCondition = '';
} else {
	$EquipCondition = 'AND ModelGroup = ' .$Equipment.'';
}


if ($Region == '') {

	$Mc = "SELECT Region,  CuTotal, CuAssigned FROM
			( SELECT count(distinct a.CustomerID) as CuTotal, c.regnName as Region  FROM sbms.machinemaster as a 
inner join sbms.branch as b on b.branchcode = a.BranchCode 
inner join sbms.region as c on c.regnID = b.regnID
WHERE a.MachineStatus = 'A' $EquipCondition AND c.regnID !='5' group by c.regnID) total

			LEFT JOIN (Select count(a.RowID) as CuAssigned , c.regnName as Region FROM sbms.customerdata as a
			inner join sbms.branch as b on b.branchID = a.Branch
			inner join sbms.region as c on c.regnID = b.regnID 
			inner join sbms.machinemaster as d on d.id = a.RowID
			WHERE a.Month = '$Month' $EquipCondition and d.MachineStatus='A' AND a.VisitType !='No Due' AND a.Status ='1'
			group by c.regnID order by c.regnID ASC ) assigned USING (Region)";
	$Mcresult = mysqli_query($conn, $Mc);

	$McNoRow = mysqli_num_rows($Mcresult);

	$return_arr[] = array('Region', 'Active Customer', 'Visited');
	while ($Mcrow = mysqli_fetch_array($Mcresult)) {
		$CustRegion = $Mcrow['Region'];
		$CusTotal = $Mcrow['CuTotal'];
		$CusAssigned = $Mcrow['CuAssigned'];

		$return_arr1[] = array(
			$CustRegion
		);

		$return_arr2[] = array(
			$CusTotal
		);

		$return_arr3[] = array(
			$CusAssigned
		);
	}

	echo json_encode(array("CustRegion" => $return_arr1, "CusTotal" => $return_arr2, "CusAssigned" => $return_arr3));

}

if ($Region !== '') {
	$Mc = "SELECT Branch,  McTotal, McAssigned FROM
			( SELECT count(distinct a.CustomerID) as McTotal, b.branchName as Branch  FROM sbms.machinemaster as a 
				inner join sbms.branch as b on b.branchcode = a.BranchCode 
				inner join sbms.region as c on c.regnID = b.regnID
				WHERE a.MachineStatus = 'A' $EquipCondition  AND c.regnID ='$Region'  group by b.branchcode) total

			LEFT JOIN (Select count(a.RowID) as McAssigned , b.branchName as Branch FROM sbms.customerdata as a
			inner join sbms.branch as b on b.branchID = a.Branch
			inner join sbms.region as c on c.regnID = b.regnID 
			inner join sbms.machinemaster as d on d.id = a.RowID
			WHERE a.Month = '$Month' $EquipCondition and d.MachineStatus='A' AND b.regnID = '$Region' AND a.VisitType !='No Due' AND a.Status ='1'
			group by b.branchID ) assigned USING (Branch)";
	$Mcresult = mysqli_query($conn, $Mc);

	$McNoRow = mysqli_num_rows($Mcresult);

	$return_arr[] = array('Region', 'Active Machine', 'Procuction Data Collected');
	while ($Mcrow = mysqli_fetch_array($Mcresult)) {
		$CustRegion = $Mcrow['Branch'];
		$CusTotal = $Mcrow['McTotal'];
		$CusAssigned = $Mcrow['McAssigned'];

		$return_arr1[] = array(
			$CustRegion
		);

		$return_arr2[] = array(
			$CusTotal
		);

		$return_arr3[] = array(
			$CusAssigned
		);
	}

	echo json_encode(array("CustRegion" => $return_arr1, "CusTotal" => $return_arr2, "CusAssigned" => $return_arr3));
}
?>
<script type="text/javascript">
	$(document).ready(function () {
		ProductionFilter();
	});

	$(document).on('change', '.filter', function () {
		ProductionFilter();
	});


	function ProductionFilter() {
		var Month = document.getElementById("Month").value;
		var Region = document.getElementById("Region").value;
		var Branch = document.getElementById("Branch").value;
		var Equipment = document.getElementById("Equipment").value;
		$.ajax({
			url: 'Customer_Graph_Filter.php',
			type: 'POST',
			data: 'Month=' + Month + '&Region=' + Region + '&Branch=' + Branch + '&Equipment=' + Equipment,
			dataType: 'JSON',
			success: function (response) {
				var CustomerRegion = response.CustRegion;
				var CustomerAssigned = response.CusAssigned;
				var CustomerTotal = response.CusTotal;

				var barChartData = {
					labels: CustomerRegion,
					datasets: [{
						label: 'Total Customers',
						backgroundColor: 'rgba(0, 158, 251, 0.5)',
						borderColor: 'rgba(0, 158, 251, 1)',
						borderWidth: 1,
						data: CustomerTotal
					}, {
						label: 'Data Collected',
						backgroundColor: 'rgba(255, 188, 53, 0.5)',
						borderColor: 'rgba(255, 188, 53, 1)',
						borderWidth: 1,
						data: CustomerAssigned
					}]
				};

				var myoption = {
					responsive: true,
					tooltips: {
						enabled: true
					},
					hover: {
						animationDuration: 1
					},
					scales: {
						yAxes: [{
							ticks: {
								beginAtZero: true,
							}
						}],
						xAxes: [{
							ticks: {
								autoSkip: false
							}
						}]
					},
					animation: {
						duration: 1,
						onComplete: function () {
							var chartInstance = this.chart,
								ctx = chartInstance.ctx;
							ctx.textAlign = 'center';
							ctx.fillStyle = "rgba(0, 0, 0, 1)";
							ctx.textBaseline = 'bottom';

							this.data.datasets.forEach(function (dataset, i) {
								var meta = chartInstance.controller.getDatasetMeta(i);
								meta.data.forEach(function (bar, index) {
									var data = dataset.data[index];
									ctx.fillText(data, bar._model.x, bar._model.y + 1);

								});
							});
						}
					},
					maintainAspectRatio: true
				};

				var ctx = document.getElementById('CustomerBarGraph').getContext('2d');
				window.myBar = new Chart(ctx, {
					type: 'bar',
					data: barChartData,
					options: myoption,
				});
			}
		});
	}

</script>

Thanks for your support

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.