我有一个小部件,其中有一个表单。我的目标是,当按下提交按钮时,一些数据会发送到 php,php 将运行一个函数来获取数据表单 db。我需要 js 文件中的数据,所以现在我将数据 jsonify 并放入一个名为 data.json 的文件中。从该文件中,我使用 jquery.ajax() 获取数据。
我的问题是:我怎样才能使它更高效?
.php
<?php
chdir('/var/www/html/vtigercrm');
require_once('include/utils/utils.php');
if(isset($_POST['id']) && !empty($_POST['id'])){
$filterdData = getChartData($_POST['id'], $_POST['maxAmount'], $_POST['minAmount']);
$file = fopen("/var/www/html/vtigercrm/include/data.json", "w");
fwrite($file, json_encode($filterdData));
fclose($file);
}
function getChartData($product_id, $maxAmount=NULL, $minAmount=NULL){
global $adb;
$maxAmountQuery = "";
$minAmountQuery = "";
if(!is_null($maxAmount) && $maxAmount != ""){
$maxAmountQuery = " AND i.quantity <= " . $maxAmount;
}
if(!is_null($minAmount) && $minAmount != ""){
$minAmountQuery = " AND i.quantity >= " . $minAmount;
}
$sales = $adb->run_query_allrecords("SELECT c.modifiedtime, i.quantity, i.listprice, i.discount_percent, i.discount_amount, CONCAT(q.quote_no, ' ', q.subject) AS quotename " .
"FROM vtiger_inventoryproductrel i " .
"INNER JOIN vtiger_crmentity c ON c.crmid = i.id " .
"INNER JOIN vtiger_quotes q ON q.quoteid = i.id " .
"WHERE q.quotestage = 'Delivered' AND i.productid = " . $product_id .
$maxAmountQuery . $minAmountQuery .
" ORDER BY c.modifiedtime ASC");
//Calculate price after discount
$salesCalculated = [];
for($i = 0; $i < count($sales); $i++){
$tmpdate = explode(" ", $sales[$i][0]);
$salesCalculated[$i][0] = $tmpdate[0];
$salesCalculated[$i][1] = $sales[$i][1];
if($sales[$i][3] == "" && $sales[$i][4] == ""){
$salesCalculated[$i][2] = $sales[$i][2] * 1;
}elseif($sales[$i][3] == ""){
$salesCalculated[$i][2] = $sales[$i][2] - ($sales[$i][4] / $sales[$i][1]);
}elseif($sales[$i][4] == ""){
$salesCalculated[$i][2] = $sales[$i][2] - ($sales[$i][2] / 100 * $sales[$i][3]);
}
$salesCalculated[$i][3] = $sales[$i][5];
}
//Add element for every item
$count = 0;
$salesScatter = [];
for($i = 0; $i < count($salesCalculated); $i++){
for($j = 0; $j < $salesCalculated[$i][1]; $j++){
$salesScatter[$count] = [];
$salesScatter[$count][0] = $salesCalculated[$i][0];
$salesScatter[$count][1] = $salesCalculated[$i][2];
$salesScatter[$count][2] = $salesCalculated[$i][3];
$count++;
}
}
//Get average and split date
$count = 0;
$mydata = [];
for($i = 0; $i < count($salesScatter); $i++){
$sum = 0;
$num = 0;
for($j = 0; $j < count($salesScatter); $j++){
if($salesScatter[$i][0] == $salesScatter[$j][0]){
$sum += $salesScatter[$j][1];
$num++;
}
}
$mydata[$count] = [];
$mydata[$count][0] = explode("-", $salesScatter[$i][0]);
$mydata[$count][1] = $salesScatter[$i][1];
$mydata[$count][2] = $sum / $num;
$mydata[$count][3] = $salesScatter[$i][2];
$count++;
}
return $mydata;
}
function getProductSales($product_id){
global $adb;
$mydata = getChartData($product_id);
$file = fopen("/var/www/html/vtigercrm/include/data.json", "w");
fwrite($file, json_encode($mydata));
fclose($file);
//Data to send to Smarty
$highest = 0;
$average = 0;
$lowest = $mydata[0][1];
for($i = 0; $i < count($mydata); $i++){
if($mydata[$i][1] > $highest){
$highest = $mydata[$i][1];
}
$average += $mydata[$i][1];
if($mydata[$i][1] < $lowest){
$lowest = $mydata[$i][1];
}
}
$average /= count($mydata);
$product = $adb->run_query_record("SELECT CONCAT(product_no, ' (', productname, ')'), unit_price " .
"FROM vtiger_products WHERE productid = " . $product_id);
$product_details = [ 'name'=>$product[0], 'unit'=>$product[1], 'highest'=>$highest, 'average'=>$average, 'lowest'=>$lowest];
return $product_details;
}
?>
.tpl
{strip}
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'include/getProductSales.php',
data: { id: {php}echo $_GET['record'];{/php} ,
maxAmount:$("#maxAmount").val(),
minAmount:$("#minAmount").val()
},
complete: function(){
drawChart();
}
});
});
});
</script>
<script src="resources/priceChart.js"></script>
<form>
<table class="table table-bordered equalSplit detailview-table">
<thead>
<tr>
<th class="blockHeader" colspan="4">
<img class="cursorPointer alignMiddle blockToggle hide" src="layouts/vlayout/skins/alphagrey/images/arrowRight.png" data-mode="hide" data-id="31">
<img style="display: inline;" class="cursorPointer alignMiddle blockToggle" src="layouts/vlayout/skins/alphagrey/images/arrowDown.png" data-mode="show" data-id="31">
Details
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Product</label>
</td>
<td class="fieldValue medium">{$PRODUCT['name']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">List Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['unit']}</td>
</tr>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Highest Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['highest']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Max. Amount</label>
</td>
<td class="fieldValue medium"><input type="text" name="maxAmount" id="maxAmount"></td>
</tr>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Average Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['average']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Min. Amount</label>
</td>
<td class="fieldValue medium"><input type="text" name="minAmount" id="minAmount"></td>
</tr>
<tr>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px">Lowest Price</label>
</td>
<td class="fieldValue medium">{$PRODUCT['lowest']}</td>
<td class="fieldLabel medium">
<label class="muted pull-right marginRight10px"></label>
</td>
<td class="fieldValue medium"><input name="submit" type="submit" value="Filter"></td>
</tr>
</tbody>
</table>
</form>
<style>
#chart_div{
margin: 20px 0px;
background-color: white;
min-height: 450px;
-webkit-box-shadow: 4px 4px 15px 0px rgba(50, 50, 50, 0.3);
-moz-box-shadow: 4px 4px 15px 0px rgba(50, 50, 50, 0.3);
box-shadow: 4px 4px 15px 0px rgba(50, 50, 50, 0.3);
}
</style>
<div id="chart_div" ></div>
{/strip}
.js
google.charts.setOnLoadCallback(drawChart);
//check window size
if (document.addEventListener)
{
window.addEventListener("resize", drawChart);
}
else if (document.attachEvent)
{
window.attachEvent("onresize", drawChart);
}
else
{
window.resize = drawChart;
}
function drawChart() {
var jsonData = $.ajax({
url: "include/getChartdata.php",
dataType: "json",
async: false
}).responseText;
var mydata = $.parseJSON(jsonData);
console.log(mydata);
var data = new google.visualization.DataTable();
data.addColumn("datetime", "Date");
data.addColumn("number", "Price");
data.addColumn({type : "string", role : "tooltip"});
data.addColumn("number", "Price (Average)");
data.addColumn({type : "string", role : "tooltip"});
var s = mydata.length;
if(s == 0){
alert("There is no data in the range you selected. Please select another range.");
}
for(var i = 0; i < s; i++ ){
data.addRow([new Date(mydata[i][0][0], mydata[i][0][1]-1, mydata[i][0][2]), mydata[i][1], mydata[i][3] + " " + mydata[i][1], mydata[i][2], 'Average of : ' + mydata[i][2]]);
}
var min = new Date(mydata[0][0][0], mydata[0][0][1]-1, mydata[0][0][2]);
min.setDate(min.getDate() - 7);
var max = new Date(mydata[s-1][0][0], mydata[s-1][0][1]-1, mydata[s-1][0][2]);
max.setDate(max.getDate() + 7);
var options = {
chartArea:{width:"80%",height:"70%"},
hAxis: {
title: "Date",
viewWindow: {
min: min,
max: max
},
gridlines: {
count: -1,
units: {
days: {
format: ["MMM dd"]
},
}
},
},
vAxis: {
title: "Price",
minValue: 0
},
legend: "none",
series: {
0: {
pointSize: 10,
dataOpacity: 0.6,
pointShape: "diamond"
},
1: {
lineWidth: 2,
color: "#509C49",
pointSize: 2
}
}
};
var chart = new google.visualization.ScatterChart(document.getElementById("chart_div"));
chart.draw(data, options);
}