More efficient way to send data from php to js - php

I have a widget that has a form in it. my goal is that when the submit button is pressed some data gets send to php which will run a function to get data form db. I need the data in the js file so right now i jsonify the data en put it in a file called data.json. from that file i get the data with jquery.ajax().
My question is: How can i make this more efficiant?
.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);
}

Why are you saving this file? Change $_POST to $_GET and make your urls and user input send parameters to the PHP. Then PHP runs the query to get the data from the DB, encodes it through JSON and returns to user, no saving into file needed. I see you're using jQuery, so $.getJSON should work for you just fine. You're writing stuff you don't need. I'm in a hurry i will explain better if needed when tonight.

Related

Upload uploading dark photo

I have a system for registering products, where the part of including photos is like this:
The code that on the part of the photos is like this:
$visualizar = '<table class="table table-bordered">
<tr>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">Tamanho <i class="fa fa-plus-circle" aria-hidden="true"></i></td>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">Quantidade</td>
<td style="text-align: center; background-color: #367FA9; color: #FFF; font-weight: bold">EAN</td>
</tr>';
$sql = mysqli_query($this->conexao,"SELECT * FROM loja_tamanho_grades WHERE IdGrades = '".$grades."';");
///$c = 0;
while($isfast = mysqli_fetch_assoc($sql))
{
$sqlTamanhos = mysqli_query($this->conexao,"SELECT * FROM loja_tamanhos WHERE IdTamanhos = '".$isfast["IdTamanhos"]."';");
$isfastTamanhos = mysqli_fetch_assoc($sqlTamanhos);
$visualizar .= '<tr>
<td style="font-weight: bold; text-align: center; font-size: 20px; font-style:Arial">
<input type="hidden" name="GradesEscolhidas[]" value="'.$grades.'">
<input type="text" name="TamanhosEscolhidos[]" style="border: 0px; width: 50px; text-align: center" readonly value="'.$isfastTamanhos["Tamanhos"].'">
</td>
<td>
<input type="number" name="QtdEscolhidos[]" class="form-control" min="0" oninput="this.value = Math.abs(this.value)" value="0">
</td>
<td>
<input type="text" name="EANEscolhidos[]" class="form-control" maxlength="17" style="width: 100%">
</td>
</tr>';
}
$visualizar .= '<tr>
<td colspan="3" class="text-left">
<label for="fotos" class="upload">Selecionar fotos <i class="fa fa-plus-circle fa-lg" aria-hidden="true"></i></label>
<input type="hidden" name="GradesFotos[]" value="'.$grades.'">
<input id="fotos" type="file" name="Fotos[]['.$grades.']" multiple>
</td>
</tr>';
//$c++;
$visualiza[] = $visualizar;
echo json_encode($visualiza);
When the user clicks sign up, it is directed to the method below:
if($_POST["Submit"] == "Cadastrar"){
$fotos = $_FILES["Fotos"];
$fotosTemp = $_FILES["Fotos"]["tmp_name"];
$dados = array_filter($_POST);
echo $metodos->cadastrarProdutos($dados,$fotos,$fotosTemp);
}
And the method cadastrarProdutos():
public function cadastrarProdutos(array $dados,$fotos,$fotosTemp)
{
...
$gradesEscolhidas = $dados["GradesEscolhidas"];
for($f = 0; $f < count($fotos['name']); $f++)
{
foreach($fotos['name'][$f] as $key => $value){
$fotosProd = $value;
$tempProd = $fotos['tmp_name'][$f];
$extensoesProd = array('png', 'jpg', 'jpeg','JPG');
$validarProd = pathinfo($fotosProd, PATHINFO_EXTENSION);
list($nomeFotoProd, $extensaoFotoProd) = explode($validarProd, $fotosProd);
$data = date("Y-m-d H:i");
$nomeFotoProd = md5($nomeFotoProd).".".$validarProd;
if($fotosProd == $fotoPrincipal[0])
{
$nomeFotoPrinc = $nomeFotoProd;
}
if(!in_array(strtolower($validarProd), $extensoesProd))
{
$_SESSION["ErroFoto"] = "Extensões permitidas: png e jpg";
$_SESSION["Erro"] = time() + 2;
}
else
{
move_uploaded_file($tempProd, '../../site/produtos/'.$nomeFotoProd);
$diretorioNormal = "../../site/produtos/";
$fotoDir = $diretorioNormal.$nomeFotoProd;
list($largura, $altura) = getimagesize($fotoDir);
if($validarProd == 'jpg' || $validarProd == 'jpeg' || $validarProd == 'JPG')
{
$imagem = imagecreatefromjpeg($fotoDir);
$x = 502;
$y = 529;
$origem_x = imagesx($imagem);
$origem_y = imagesy($imagem);
if($origem_x > $origem_y)
{
$final_x = $x;
$final_y = floor($x * $origem_y / $origem_x);
$f_x = 0;
$f_y = round(($y / 2) - ($final_y / 2));
}
else
{
$final_x = floor($y * $origem_x / $origem_y);
$final_y = $y;
$f_x = round(($x / 2) - ($final_x / 2));
$f_y = 0;
}
$miniatura = imagecreatetruecolor($x, $y);
imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $x, $y, $largura, $altura);
imagejpeg($miniatura,$fotoDir,9);
}
if($validarProd == 'png')
{
$imagem = imagecreatefrompng($fotoDir);
$x = 502;
$y = 529;
$origem_x = imagesx($imagem);
$origem_y = imagesy($imagem);
if($origem_x > $origem_y)
{
$final_x = $x;
$final_y = floor($x * $origem_y / $origem_x);
$f_x = 0;
$f_y = round(($y / 2) - ($final_y / 2));
}
else
{
$final_x = floor($y * $origem_x / $origem_y);
$final_y = $y;
$f_x = round(($x / 2) - ($final_x / 2));
$f_y = 0;
}
$miniatura = imagecreatetruecolor($x, $y);
imagecopyresampled($miniatura, $imagem, 0, 0, 0, 0, $x, $y, $largura, $altura);
imagepng($miniatura,$fotoDir,9);
}
$query = "INSERT INTO loja_fotos_produtos(IdProdutos,IdGrades,Fotos) VALUES(?,?,?);";
$stmt = mysqli_prepare($this->conexao,$query);
mysqli_stmt_bind_param($stmt,"sss",$idProduto,$key,$value);
mysqli_stmt_execute($stmt);
if(mysqli_affected_rows($this->conexao) > 0)
{
$_SESSION["Sucesso"] = time() + 5;
}
}
}
}
}
Registration usually occurs, but the photos are as follows. How can I fix this?

Session variables from for not stored and accessible on other pages

I hope I'm not asking a question already answered, I have searched extensively on the site for an answer to my problem but can not manage to find a solution.
I have the following problem.
I have a form in which is a shopping cart, it is supposed to apply a coupon and then save those values so they can be used later on different pages.
For some reason however, these session variables are not saved.
My form looks like this:
<?php
session_start();
$cart_custom = json_decode($_COOKIE['view_cart_custom_fab'],true);
//print_r($cart_custom);
include_once("inc/header.php");
//set_add_to_cart_cookie();
$fetch_user_info = mysqli_query($conn,"SELECT * FROM `st_customer` WHERE `email`= '{$_SESSION['USER_EMAIL']}'");
$fetch_info = mysqli_fetch_array($fetch_user_info);
$size_id = ($_REQUEST['id'] ? $_REQUEST['id'] : $_COOKIE['fabric_size_id']);
$fabric_id = $_COOKIE['fabric_id'];
$fabric_back = $_COOKIE['fabric_back'];
$shirts = $_COOKIE['shirts'];
$fabric_arms = $_COOKIE['fabric_arms'];
$fabric_pocket = $_COOKIE['fabric_pocket'];
$fabric_cuff = $_COOKIE['fabric_cuff'];
$fabric_boy_border = $_COOKIE['fabric_boy_border'];
$fabric = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_id'");
$fabric_record = mysqli_fetch_array($fabric);
$fabric_back_data = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_back'");
$fabric_back_record = mysqli_fetch_array($fabric_back_data);
$arms = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_arms'");
$arms_record = mysqli_fetch_array($arms);
$pocket = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_pocket'");
$pocket_record = mysqli_fetch_array($pocket);
$cuff = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_cuff'");
$cuff_record = mysqli_fetch_array($cuff);
$border = mysqli_query($conn,"SELECT * FROM `st-fabrics` where `id` = '$fabric_boy_border'");
$border_record = mysqli_fetch_array($border);
$select_size = mysqli_query($conn,"SELECT * FROM `st_sizes` where `size_id` = '$size_id'");
$user_select_size = mysqli_fetch_array($select_size);
$model_id = $user_select_size['size_model'];
$model = mysqli_query($conn,"SELECT * FROM `st_model` where `model_id` = '$model_id'");
$model_name = mysqli_fetch_array($model);
if($shirts=="half_shirt"){
$shirt = $user_select_size['half_sleeve'];
}
if($shirts=="full_tshirt"){
$shirt = $user_select_size['full_sleeve'];
}
$cm1 = $fabric_record['fabric_price']/10;
$cm2 = $arms_record['fabric_price']/10;
$cm3 = $fabric_back_record['fabric_price']/10;
$front_size = ($cm1*$user_select_size['front']*100);
$back_size = ($cm3*$user_select_size['size_back']*100);
$arms_size = ($cm2*$shirt*100);
$front_back_total = $user_select_size['front']+$user_select_size['size_back'];
$custom_total = ($front_size+$back_size+$arms_size);
if(isset($_POST['apply_coupon_btn'])){
$query_coupon = mysqli_query($conn,"SELECT * FROM `st_coupon` WHERE `coupon_code`='{$_POST['coupon_apply']}' AND `status`='1'");
$fetch_coupon = mysqli_fetch_array($query_coupon);
$message = "tmp2";
if(isset($fetch_coupon)){
$_SESSION['coupon_data'] = $fetch_coupon;
$check_user_id = mysqli_query($conn,"SELECT * FROM `st_order` as so JOIN `st_coupon` as sc on so.`coupon_id`=sc.`coupon_id` WHERE sc.`coupon_code`='{$_POST['coupon_apply']}' AND so.`user_id`={$_SESSION['user_id']}");
$message = "tmp3";
if(mysqli_num_rows($check_user_id)){
$message = "U hebt deze kortingscode reeds gebruikt";
}else{
if($fetch_coupon['coupon_type'] == "price"){
$_SESSION['price_coupon_price'] = $fetch_coupon['coupon_value'];
unset($_SESSION['price_coupon_percent']);
}elseif($fetch_coupon['coupon_type'] == "percent"){
$_SESSION['price_coupon_percent'] = $fetch_coupon['coupon_value'];
unset($_SESSION['price_coupon_price']);
}
}
}else{
$message = "Foute kortingscode";
}
}
if(isset($_POST['remove_coupon_btn'])){
unset($_SESSION['price_coupon_percent']);
unset($_SESSION['price_coupon_price']);
unset($_SESSION['coupon_data']);
unset($_SESSION['price_coupon_value']);
header("location: winkelwagen.php");
}
if(isset($_POST['update_cart']))
{
echo "update cart";
foreach($_POST['custom_qty_cart'] as $key=>$qtys){
$cart_custom[$key]['price']['qty'] = $qtys;
}
setcookie('view_cart_custom_fab', json_encode($cart_custom), time() + (86400 * 2), "/");
setcookie('custom_qty', $_POST['custom_qty'], time() + (86400 * 2), "/");
$custom_total = $custom_total*$_POST['custom_qty'];
setcookie('custom', $custom_total, time() + (86400 * 2), "/");
foreach($_POST["qty"] as $key => $qty) { //Print each item, quantity and price.
$id = $_POST["product_id"][$key];
$_SESSION["products"][$id]["fabric_qty"] = $qty;
}
header("location: winkelwagen.php");
}
if(isset($_POST['checkout_btn'])){
if($_SESSION['USER_EMAIL']){
header("location: afrekenen.php");
}else{
header("location: winkelwagen.php#login-modelbox");
}
}
?>
<div class="container">
<h4><?php echo $_SESSION['price_coupon_value']; ?></h4>
<h4><?php echo $_SESSION['coupon_data']; ?></h4>
<div class="main_content fabric-content margin_top">
<?php
?>
<?php if (!empty($_SESSION["products"]) || count($cart_custom) > 0) { ?>
<form method="POST" action="winkelwagen.php" style="width:60%; float:left; position:relative; left: 50%;">
<table class="margin_top" style="float: left; position: relative; left: -50%;">
<tr>
<th data-field="id" colspan="1" style="width: 15%;"></th>
<th data-field="id" colspan="1" style="width: 35%;">Naam</th>
<th data-field="id" colspan="1" style="width: 35%;">Aantal</th>
<th data-field="id" colspan="1" style="width: 15%;">Prijs</th>
</tr>
<?php if(count($cart_custom) > 0){ ?>
<?php
$total_price = 0;
foreach($cart_custom as $key=>$val){
$cookie_model = $cart_custom[$key]['model'];
$cookie_price = $cart_custom[$key]['price'];
$model_name = $cookie_model['model'];
if($model_name == "wranglan_model"){
$model_img = "image/t-shirt.png";
}elseif($model_name == "round_model"){
$model_img = "image/t-shirt.png";
}
$model_qty = str_replace(",",".",$cookie_price['qty']);
$model_price = $model_qty * $cookie_price['ttl_price'];
$total_price = $model_qty * $cookie_price['ttl_price'] + $total_price;
if(isset($_GET['remove_id'])){
unset($cart_custom[$_GET['remove_id']]);
setcookie('view_cart_custom_fab', json_encode($cart_custom), time() + (86400 * 2), "/");
header("location: winkelwagen.php");
}
?>
<tr>
<td colspan='1' style="width: 15%;">
<img src='<?php echo $model_img; ?>' alt='' class='img_table responsive_img' />
</td>
<td colspan='1' style="width: 35%;">
T-shirt op smaak
</td>
<td colspan='1' style="width: 35%;">
<input id='update_cart' name='update_cart' type='hidden' value='' />
<input class="qty" type="text" name="custom_qty_cart[<?php echo $key; ?>]" value="<?php echo $model_qty; ?>" style="width: 20%; text-align:right;"/>
<input name='Update' style="width: 18px; vertical-align:bottom" type='image' value='update_cart' src='/image/update.jpg' alt='Update' onclick = "return setHidden('update_cart');" />
<img src="/image/recycle.jpg" style="width: 18px; vertical-align:bottom">
</td>
<td colspan='1' style="width: 15%;">
<?php echo price_format($model_price); ?>
</td>
</tr>
<?php
}
?>
<?php } ?>
<?php if(!empty($_SESSION["products"])){?>
<?php
if (isset($_SESSION["products"]) && count($_SESSION["products"]) > 0) {
$total = 0;
$list_tax = '';
foreach ($_SESSION["products"] as $product) { //Print each item, quantity and price.
//print_r($_SESSION["products"]);
$product_name = $product["fabric_name"];
$product_id = $product["id"];
//$product_qty = ($product["fabric_qty"] > 1 ? $product["fabric_qty"]:1);
$product_qty = str_replace(",",".",$product["fabric_qty"]);
//$product_price = ($product_qty>1 ? $product["fabric_price"] * $product_qty : $product["fabric_price"]);
$product_price = ($product["fabric_price"] * $product_qty);
$product_code = $product["product_code"];
$product_color = $product["product_color"];
$product_size = $product["product_size"];
$item_price = $product_price;
$total_cost_price = $total_cost_price + $item_price;
//$item_price = sprintf("%01.2f",($product_price * $product_qty)); // price x qty = total item price
if(isset($_GET['removeid'])){
unset($_SESSION["products"][$_GET['removeid']]);
header("location: winkelwagen.php");
}
$cart_box .=
"<tr><td colspan='1' style='width: 15%'><img src='admin/images/fabric/" . $product['fabric_texture'] . "' alt='' class='img_table responsive_img' /></td>
<td colspan='1' style='width: 35%'>$product_name</td>
<td colspan='1' style='width: 35%'>
<input id='update_cart' name='update_cart' type='hidden' value='' />
<input type='text' name='qty[]' class='qty' min='1' max='100' value='".$product_qty."' style='width: 20%; text-align:right;'/>
<input name='Update' style='width: 18px; vertical-align:bottom' type='image' value='update_cart' src='/image/update.jpg' alt='Update' onclick = 'return setHidden('update_cart');' />
<a href='?removeid=$product_id' style='width: 18px; vertical-align:bottom'><img src='/image/recycle.jpg' style='width: 18px; vertical-align:bottom'></a>
<input type='hidden' name='product_id[]' value='".$product_id."' /></td>
<td colspan='1' style='width: 15%'>".price_format($item_price)."</td>";
$subtotal = ($product_price * $product_qty); //Multiply item quantity * price
$total = ($total + $subtotal); //Add up to total price
}
$grand_total = $total + $shipping_cost; //grand total
foreach ($taxes as $key => $value) { //list and calculate all taxes in array
$tax_amount = round($total * ($value / 100));
$tax_item[$key] = $tax_amount;
$grand_total = $grand_total + $tax_amount;
}
foreach ($tax_item as $key => $value) { //taxes List
$list_tax .= $key . ' ' . $currency . sprintf("%01.2f", $value) . '<br />';
}
$shipping_cost = ($shipping_cost) ? 'Shipping Cost : ' . $currency . sprintf("%01.2f", $shipping_cost) . '<br />' : '';
echo $cart_box;
}
?>
<?php } ?>
<?php
$fetch_shipping_price = mysqli_query($conn,"SELECT * FROM `st_custom_price` WHERE `meta_key`='shipping'");
$fetch_price = mysqli_fetch_array($fetch_shipping_price);
$shipping_price = $fetch_price['meta_price'];
$product_total = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']);
if($_SESSION['price_coupon_price']){
$total_amount = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']) - $_SESSION['price_coupon_price'];
$_SESSION['price_coupon_value'] = $_SESSION['price_coupon_price'];
}elseif($_SESSION['price_coupon_percent']){
$total_amount = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']);
$percent_total = ($_SESSION['price_coupon_percent'] / 100) * $total_amount;
$_SESSION['price_coupon_value'] = $percent_total;
$total_amount = $total_amount - $percent_total;
}else{
$total_amount = $total_price + $total_cost_price + ($price_detail['ttl_price']*$price_detail['qty']);
}
$ttl_ship = $total_amount + $shipping_price;
setcookie('total_cost', $ttl_ship, time() + (86400 * 2), "/");
setcookie('total_cost', $ttl_ship, time() + (86400 * 2), "/");
?>
<?php if(!empty($total_amount) || count($cart_custom) > 0){ ?>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">Totaal</th>
<th data-field="id" colspan="1" style="width: 15%;"> <?php echo price_format($product_total); ?></th>
</tr>
<?php if($_SESSION['price_coupon_price'] || $_SESSION['price_coupon_percent']){
$discount_type = ($_SESSION['coupon_data']['coupon_type'] == "price" ? " €" : " percent ");
?>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">
<input id='remove_coupon_btn' name='remove_coupon_btn' type='hidden' value='' />
Kortingscode <?php echo $_SESSION['coupon_data']['coupon_name']; ?><input name='remove_coupon_btn' style="width: 18px; vertical-align:bottom" type='image' value='remove_coupon_btn' src='/image/recycle.jpg' alt='Remove coupon' onclick = "return setHidden('remove_coupon_btn');" />
</th>
<th style="width: 15%;"><?php echo price_format($total_amount-$product_total); ?></th>
</tr>
<?php } ?>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">Verzendingskosten</th>
<th data-field="id" colspan="1" style="width: 15%;"> <?php echo price_format($shipping_price); ?></th>
</tr>
<tr>
<th data-field="id" colspan="3" style="width: 85%;">Te betalen</th>
<th data-field="id" colspan="1" style="width: 15%;"> <?php echo price_format($ttl_ship); ?></th>
</tr>
</table>
<?php echo $message; ?>
<div class="more-products-pagination" style="float: left; position: relative; left: -50%;">
<div class="coupon_row" style="margin:5px 20px">
<?php if($_SESSION['price_coupon_price'] || $_SESSION['price_coupon_percent']){ ?>
<?php } else { ?>
<ul>
<li>Kortingscode</li>
<li><input type="text" name="coupon_apply" value=""><input type="submit" name="apply_coupon_btn" value="Toepassen" class="add_to_cart_btn" style="border: 1px solid #fff; display: inline-block;float: right;"></li>
</ul>
<?php } ?>
</div>
<div class="pagination_btn pagination_btn_right">
<input type="submit" class="add_to_cart_btn" value="Afrekenen" name="checkout_btn">
</div>
</div>
<?php } ?>
</form>
<?php }else {
echo "Geen producten in uw winkelwagen.";
}?>
</div>
</div>
<script language="javascript">
function setHidden(whichButton)
{
var element = document.getElementById(whichButton);
element.value = whichButton;
return true;
}
</script>
<?php
include_once("inc/footer.php");
?>
<style>
table {
border-collapse: collapse;
width: 100%;
background: rgba(253, 245, 208,0.6);
box-shadow: 0px 0px 2px #C1C1C1;
}
th, td {
text-align: left;
padding: 8px;
color:#444;
}
td{
}
th {
background-color: #BD3F6F;
color: white;
font-weight: 400;
font-size: 16px;
}
</style>
When I then try to access the variable $_SESSION['coupon_data'] on a different page this does not work, it is empty.
I set the variable here in this code:
if(isset($_POST['apply_coupon_btn'])){
$query_coupon = mysqli_query($conn,"SELECT * FROM `st_coupon` WHERE `coupon_code`='{$_POST['coupon_apply']}' AND `status`='1'");
$fetch_coupon = mysqli_fetch_array($query_coupon);
$message = "tmp2";
if(isset($fetch_coupon)){
$_SESSION['coupon_data'] = $fetch_coupon;
..
}
And then I call the next page here:
if(isset($_POST['checkout_btn'])){
if($_SESSION['USER_EMAIL']){
header("location: afrekenen.php");
}else{
header("location: winkelwagen.php#login-modelbox");
}
}
Even if I call the update of the cart items in this same page, the session variables disapear for some reason which I do not understand:
if(isset($_POST['update_cart']))
{
echo "update cart";
foreach($_POST['custom_qty_cart'] as $key=>$qtys){
$cart_custom[$key]['price']['qty'] = $qtys;
}
setcookie('view_cart_custom_fab', json_encode($cart_custom), time() + (86400 * 2), "/");
setcookie('custom_qty', $_POST['custom_qty'], time() + (86400 * 2), "/");
$custom_total = $custom_total*$_POST['custom_qty'];
setcookie('custom', $custom_total, time() + (86400 * 2), "/");
foreach($_POST["qty"] as $key => $qty) { //Print each item, quantity and price.
$id = $_POST["product_id"][$key];
$_SESSION["products"][$id]["fabric_qty"] = $qty;
}
header("location: winkelwagen.php");
}
I am utterly baffled and hope someone can help me out.
issue resolved, turns out there was another call to session_start in one of the includes which was creating a separate session and hence not allowing the correct globalisation.

Editing MySQL row via POST form

I've encountered a problem which i'll try to describe below...
Let's say i've got a button for each table row (table is created by acquiring the data from the database...). the button sends a massive of values via post.
<button value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'>EDIT</button>
I've written a function to explode the values of the massive and fill the inputs on the same page.
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
}
Next comes the function to edit the row in the database.
function editEvent ($id, $type, $date, $price, $descr){
$mysqli = new mysqli($GLOBALS["serverHost"], $GLOBALS["serverUsername"], $GLOBALS['serverPassword'], $GLOBALS['dbName']);
$stmt = $mysqli->prepare("UPDATE events_archive SET eventType='?', eventDate='?', eventPrice='?', eventDescr='?' WHERE id='?'");
$stmt->bind_param("ssdss", $type, $date, $price, $descr, $id);
$stmt->execute();
header("Refresh:0");
if($stmt->execute()){
$eventNotice="Event successfully updated!";
}else{
$eventNotice = "Failed to save...";
}
return $eventNotice;
}
And, of course, the usage of the function which apparently doesnt work. The page just refreshes and nothing happens.
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr']) && !empty($eventId)){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
So basically, gets values from the row -> fills them into inputs in the same page -> if $eventId is set then updates the row, if not - creates a new row (diff. function)
Could anyone give me a tip or help solving the problem? I've been trying to understand the issue and failed dramatically...
<?php
require ("functions.php");
var_dump($_POST);
//kas on sisseloginud, kui ei ole siis
//suunata login lehele
//kas ?logout on aadressireal
if (isset($_GET['logout'])){
session_destroy();
header("Location: login.php");
}
if (!isset ($_SESSION["userId"])){
header("Location: login.php");
}
$confirm = "";
$eventNotice = "";
$eventTypeError = "";
$eventDateError = '';
$eventPriceError = '';
$eventDescrError = '';
$eventType = '';
$eventDescr = '';
$eventPrice = '';
$eventDate = date("Y-m-d");
if (isset ($_POST["eventType"])){
if (empty($_POST['eventType'])){
$eventTypeError = "Please choose the event type!";
} else {
$eventType = $_POST["eventType"];
}
}
if (isset ($_POST ["eventDate"])){
if (empty ($_POST ["eventDate"])){
$eventDateError = "Please choose the date!";
} else {
$eventDate = $_POST["eventDate"];
}
}
if (isset ($_POST ["eventPrice"])){
if (empty ($_POST ["eventPrice"])){
$eventPriceError = "Please type in the price!";
} else {
$eventPrice = $_POST["eventPrice"];
}
}
if (isset ($_POST ["eventDescr"])){
if (empty ($_POST ["eventDescr"])){
$eventDescrError = "Please type in the description!";
}elseif (strlen($_POST["eventDescr"])< 10) {
$eventDescrError = "Description must be longer than 10 symbols!";
$eventDescr = $_POST['eventDescr'];
}else{
$eventDescr = $_POST['eventDescr'];
}
}
$event = getAllEvents();
if(!empty($_POST['delValue'])) {
delEvent($_POST['delValue']);
}
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
echo ($eventId);
echo ($eventDate);
echo ($eventPrice);
echo ($eventType);
echo ($eventDescr);
}
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr'])){
if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}elseif(!isset($_POST['editValue'])){
$eventNotice = newEvent(cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
}
?>
<html>
<style>
#import "styles.css";
ul.tab {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
ul.tab li {float: left;}
ul.tab li a {
display: inline-block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
transition: 0.3s;
font-size: 17px;
}
ul.tab li a:hover {
background-color: #ddd;
}
ul.tab li a:focus, .active {
background-color: #ccc;
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
<body>
<form method ="post">
<table class="table1">
<tr>
<td style="text-align:center"><h1>Data</h1></td>
</tr>
<tr>
<th><h2>Profile</h2></th>
</tr>
<tr>
<td>
<table class="table2">
<tr>
<td colspan="3"">Welcome <?=$_SESSION['email'];?>!</td>
</tr>
<tr>
<td colspan="3" style="text-align:center">Log out</td>
</tr>
</table>
<tr>
<td>
<tr>
<td>
<ul class="tab">
<li>Add/edit</li>
<li>Archive</li>
</ul>
<div id="Add/edit" class="tabcontent">
<input type="hidden" value='eventId'>
<table class="table2">
<tr>
<td>Event type:<span class = 'redtext'>*</span></td>
<td style="text-align:left">
<select name="eventType">
<?php if(empty($eventType)){?>
<option value="" selected>Choose here</option>
<?php } else { ?>
<option value="">Choose here</option>
<?php } ?>
<?php if($eventType == "Planned service"){?>
<option value="Planned service" selected>Planned service</option>
<?php } else { ?>
<option value="Planned service">Planned service</option>
<?php } ?>
<?php if($eventType == "Unplanned service"){?>
<option value="Unplanned service" selected>Unplanned service</option>
<?php } else { ?>
<option value="Unplanned service">Unplanned service</option>
<?php } ?>
<?php if($eventType == "Fuel checks"){?>
<option value="Fuel checks" selected>Fuel checks</option>
<?php } else { ?>
<option value="Fuel checks">Fuel checks</option>
<?php } ?>
<?php if($eventType == "Tuning"){?>
<option value="Tuning" selected>Tuning</option>
<?php } else { ?>
<option value="Tuning">Tuning</option>
<?php } ?>
<?php if($eventType == "Car accident"){?>
<option value="Car accident" selected>Car accident</option>
<?php } else { ?>
<option value="Car accident">Car accident</option>
<?php } ?>
</select>
</td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventTypeError?></td></tr>
<tr>
<td>Date:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input name="eventDate" type ="date" min="1900-01-01" max = "<?=date('Y-m-d'); ?>" value = "<?=$eventDate?>" placeholder="YYYY-MM-DD"></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDateError?></td></tr>
<tr>
<td>Price:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input type="text" name="eventPrice" placeholder="ex. 15.50" onkeypress="return onlyNumbersWithDot(event);" / value = "<?=$eventPrice?>"></td>
<script type="text/javascript">
function onlyNumbersWithDot(e) {
var charCode;
if (e.keyCode > 0) {
charCode = e.which || e.keyCode;
}
else if (typeof (e.charCode) != "undefined") {
charCode = e.which || e.keyCode;
}
if (charCode == 46)
return true
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventPriceError?></td></tr>
<tr>
<td>Description:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><textarea name="eventDescr" cols="50" rows="10" placeholder="Describe event here..."><?=$eventDescr?></textarea></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDescrError?></td></tr>
<tr>
<td colspan="3" style="text-align:center"><button type ="submit" value = "Submit">Save</button></td>
</tr>
<tr>
<td colspan="3" style="text-align:center"><p class = "redtext"><?=$eventNotice;?></p></td>
</tr>
</table>
</div>
</form>
<form method="post">
<div id="Archive" class="tabcontent">
<table class="table2">
<tr>
<td colspan="3"">
<?php
$html = "<table>";
$html .= "<tr>";
$html .= "<th>Event type</th>";
$html .= "<th>Date</th>";
$html .= "<th>Price(€)</th>";
$html .= "<th>Description</th>";
$html .= "<th>Delete</th>";
$html .= "<th>Edit</th>";
$html .= "</tr>";
foreach($event as $e){
$html .= "<tr>";
$html .= "<td>$e->eventType</td>";
$html .= "<td>$e->eventDate</td>";
$html .= "<td>$e->eventPrice</td>";
$html .= "<td>$e->eventDescr</td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId' name='delValue' onclick=\"return confirm('Do you really want to delete this row?')\"><img src='delete.png' width='20' height='20'></button></td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'><img src='edit.png' width='20' height='20'></button></td>";
$html .= "</tr>";
}
$html .= "</table>";
echo $html;
?>
</td>
</tr>
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
</td>
</tr>
</table>
</td>
</tr>
</div>
</form>
</body>
</html>
Looking forward to Your help!
Best regards :)
if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}

taxi fare calculation using php with google distance matrix api v2

I want to have a taxi fare calculation in my website.
I have the following requirements:
If Google Distance Matrix calculation show following distance kilometers, the rate should go like this:
From 0 -10km = $65 (fixed price) + 11%
10km = $70 + 11%
15km = $80 + 11%
20km = $90 + 11%
25km = $100 + 11%
30km = $120 + 11%
30km above = $4 / km
I put rate as $2 per km from 10 km above till 30km + $50 extra which result :
if taxi if drived for
20km = 20km × $2 + $50 = $90 + 11%
21km = 21km × $2 + $50 = $92 + 11%
22km = 22km × $2 + $50 = $94 + 11% and so on
but i am dont know to calculate the fixed price of $65 which is the fix rate for below 10 km distance and $120 rate for 30 km and 30km above ie $4/km .
the script i used for Google Distance Matrix is to show $2/km + $50 fix : (I have not added 11% in this script)
<script src="http://maps.google.com/maps?file=api&v=2&key=_MY_API_KEY"
type="text/javascript"></script>
<?php
$rate=2;
$extra=50;
?>
<script type="text/javascript">
var geocoder, location1, location2, gDir;
var map;
var gdir;
var geocoder = null;
var addressMarker;
var directionsPanel;
var directions;
function initialize() {
geocoder = new GClientGeocoder();
gDir = new GDirections();
GEvent.addListener(gDir, "load", function() {
var drivingDistanceMiles = gDir.getDistance().meters / 1000;
var drivingDistanceround =
Math.round(drivingDistanceMiles*100)/100;
var cost = ((drivingDistanceMiles * <?php echo $rate; ?>) + (<?php
echo $extra; ?>))
<?php echo $rate; ?>) + (<?php echo
$extra; ?>))
};
*/
var fare=cost;
var fare = Math.round(fare*100)/100;
document.getElementById('results').innerHTML = '<table
width="100%" style="border-collapse:collapse; padding-top:3px;"><tr><td rowspan="2"
width="35"><img src="images/rates.png"></td><td><strong>Distance: </strong>' +
drivingDistanceround + ' Kilemeters</td></tr><tr><td><strong>Estimated Cost:
</strong>$ ' + fare + '</td></tr></table>';
});
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(-33.722626, 150.810585), 10);
gdir = new GDirections(map, document.getElementById("directions"));
GEvent.addListener(gdir, "load", onGDimrectionsLoad);
GEvent.addListener(gdir, "error", handleErrors);
}
}
function setDirections(fromAddress, toAddress, locale) {
gdir.load("from: " + fromAddress + " to: " + toAddress);
}
function showLocation() {
geocoder.getLocations(document.forms[0].from.value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first
address");
}
else
{
location1 = {lat:
response.Placemark[0].Point.coordinates[1], lon:
response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(document.forms[0].to.value, function
(response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode
the second address");
}
else
{
location2 = {lat:
response.Placemark[0].Point.coordinates[1], lon:
response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
gDir.load('from: ' + location1.address + '
to: ' + location2.address);
}
});
}
});
///////////////////////////////////////////////////////////
var directionsPanel;
var directions;
directionsPanel = document.getElementById("route");
directions = new GDirections(map, directionsPanel);
directions.load("from: "+document.forms[0].from.value+" to:
"+document.forms[0].to.value);
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<table width="915" border="2" cellpadding="0" cellspacing="0" bordercolor="#FF9F0F"
style="border-collapse:collapse">
<tr>
<td bgcolor="#FFFF99" style="padding:10px;"><table width="905" border="0"
cellspacing="0" cellpadding="0">
<tr>
<td><div id="map_canvas" style="width: 914px; height: 480px; border: solid 1px
#336699"></div></td>
</tr>
<tr>
<td><div id="form" style="width: 904px; text-align:center; border: solid 1px
#336699; background:#d1e1e4;">
<form action="#" onsubmit="document.getElementById('route').innerHTML='';
showLocation(); setDirections(this.from.value, this.to.value); return false;">
<p style="font-family:Tahoma; font-size:8pt;">From:
<input id="fromAddress" type="text" onblur="if(this.value=='')
this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)
this.value='';" value="Street Name City, State" maxlength="50" size="26" name="from"
style="font-family:Tahoma; font-size:8pt;" />
To:
<input id="toAddress" type="text" onblur="if(this.value=='')
this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue)
this.value='';" value="Street Name City, State" maxlength="50" size="26" name="to"
style="font-family:Tahoma; font-size:8pt;"/>
<input class="submit" name="submit" type="submit" value="Calculate"
style="font-family:Tahoma; font-size:8pt;" />
</p>
<div id="results" style="font-family:Tahoma; font-size:8pt; text-align:left;
padding-left:5px; padding-bottom:5px;"></div>
<div id="route" style="font-family:Tahoma; font-size:8pt; text-align:left;
padding-left:5px; padding-bottom:5px;"></div>
</form>
</div></td>
</tr>
</table></td>
</tr>
</table>
</body>
I would like to suggest you to go for Google Maps API V3, here is my tested script as per your requirement, and as per your earlier script, I would suggest to go for #Pierre-Francoys Brousse script for rates,
<?php
session_start();
$rate = 2;
$extra = 50;
$fix = 65;
$above = 110;
$next=55;
$min=3;
$cons = 4;
//}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Taxi Fare Calculation using PHP with GOOGLE MAPS API V3</title>
<style type="text/css">
html {
height: 100%
}
body {
height: 100%;
margin: 0px;
padding: 0px;
font-family:tahoma;
font-size:8pt;
}
#total {
font-size:large;
text-align:center;
font-family:Georgia, “Times New Roman”, Times, serif;
color:#990000;
margin:5px 0 10px 0;
font-size:12px;
width:374px;
}
input {
margin:5px 0px;
font-family:tahoma;
font-size:8pt;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
//<![CDATA[
var map = null;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var Australia = new google.maps.LatLng(-25.085599,133.66699);
var mapOptions = {
center : Australia,
zoom : 4,
minZoom : 3,
streetViewControl : false,
mapTypeId : google.maps.MapTypeId.ROADMAP,
zoomControlOptions : {style:google.maps.ZoomControlStyle.MEDIUM}
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
//Find From location
var fromText = document.getElementById('start');
var fromAuto = new google.maps.places.Autocomplete(fromText);
fromAuto.bindTo('bounds', map);
//Find To location
var toText = document.getElementById('end');
var toAuto = new google.maps.places.Autocomplete(toText);
toAuto.bindTo('bounds', map);
//
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
/*var control = document.getElementById('control');
control.style.display = 'block';
map.controls[google.maps.ControlPosition.TOP].push(control);*/
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
computeTotalDistance(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000;
/*Start Calculating Distance Fair*/
if (10>total){
var cost = <?php echo $fix; ?>;
}
else if (10<total && 20>total)
{
var cost = ((total * <?php echo $rate; ?>) + (<?php echo $extra; ?>));
}
else if (20<total && 30>total)
{
var cost = ((total * <?php echo $rate; ?>) + (<?php echo $next; ?>));
}
else if (30<total && 50>total)
{
var cost = (((total - 30) * <?php echo $cons; ?>) + (<?php echo $above; ?>));
}
else
{
var cost = (((total - 50) * <?php echo $min; ?>) + 130);
}
var fare = cost * 0.11 + cost;
var fare = Math.round(fare*100)/100;
/*Distance Fair Calculation Ends*/
document.getElementById("total").innerHTML = "Total Distance = " + total + " km and FARE = $" + fare;
}
function auto() {
var input = document.getElementById[('start'), ('end')];
var types
var options = {
types: [],
componentRestrictions: {country: ["AUS"]}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onLoad="initialize()">
<table width="380px" border="2" cellpadding="0" cellspacing="0" bordercolor="#FF9F0F" style="border-collapse:collapse">
<tr>
<td bgcolor="#FFFF99" style="padding:5px;">
<table width="375px" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><div id="map_canvas" style="width: 374px; height: 300px; border: solid 1px #336699"></div></td>
</tr>
<tr>
<td><div id="form" style="width:374px; text-align:center; border: solid 1px #336699; background:#d1e1e4;">
From:
<input type="text" id="start" size="60px" name="start" placeholder="Enter Location From">
<br />
To:
<input size="60px" type="text" id="end" name="end" placeholder="Enter Destination ">
<input type="button" value="Calculate" onClick="calcRoute();">
<div id="total"></div>
</div></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
If your question how can you have a fix price or a varying 'rate', why don't you just an if/else or a switch/case logic?
Also, why are you injecting php when this could be done in javascript?
Instead of
var drivingDistanceMiles = gDir.getDistance().meters / 1000;
var drivingDistanceround = Math.round(drivingDistanceMiles*100)/100;
var cost = ((drivingDistanceMiles * <?php echo $rate; ?>) + (<?php echo $extra; ?>))
<?php echo $rate; ?>) + (<?php echo $extra; ?>))
Why not just do
var rate = 2;
var extra = 50;
taxModifier = 1.11; //11%
//...
var drivingDistanceMiles = gDir.getDistance().meters / 1000;
var drivingDistanceround = Math.round(drivingDistanceMiles*100)/100;
var cost;
if (drivingDistanceMiles < 10){
cost = 65;
} else if( drivingDistanceMiles >= 10 && drivingDistanceMiles < 30) {
cost = (drivingDistanceMiles * rate + extra) * taxModifier ;
} else {
cost = drivingDistanceMiles * 4. * taxModifier ;
}

Search and play YouTube results using API, Javascript, or PHP

I want to create something where I can search a youtube video and it automatically plays all results one after the other. I've been searching the youtube api and havent found anything that relates. Anyone know of a place to get started? I know Javascript, PHP and MySQL, if someone had a script or place to start I would greatly appreciate it.
You're right the YouTube API is way too complicate to find the answer but here is a good Getting Started guide.
Anyway Take a look at Youtube Simple Embed.
This page allows you to try Google Data API online (without programming) to get an idea what you can do. Also here is the API documentation for YouTube search.
I've used javasript's arrays in my web for playing Youtube videos continuously. Please try it at the address below:
http://play-videos.url.ph/v3/search-play.html
tit = []; vid = [];
portion = 50; // portion should be <= 50
var maxRes = portion;
var nextPageToken;
var searchText = "";
var want = 150;
sum = 0; sumN = 0;
function start(num){
want = num;
searchVid()
}
function searchVid(PageToken){
var searchText= $('#searchtext1').val();
$('#response1').html("<b>Searching for "+searchText+"</b>");
$.get(
"https://www.googleapis.com/youtube/v3/search",{
part : 'snippet',
q : searchText,
maxResults : maxRes, /* 50 */
pageToken : PageToken,
key: 'AIz*********************************zm4'},
/* REPLACE with your API KEY */
function myPlan(response){
nextPageToken=response.nextPageToken;
var resultCount = response.pageInfo.totalResults;
stList = '';
if(want >= resultCount){ want = resultCount}
itemsLen = response.items.length;
for (var i=0; i<response.items.length;i++){
var videoID =response.items[i].id.videoId;
if(typeof videoID != 'undefined'){
var titSt =response.items[i].snippet.title;
vid.push(videoID);
tit.push(titSt);
ss='<tr>'+
'<td style="width:80px;">'+
'<img width="80" height="60" src="http://img.youtube.com/vi/'+
videoID +'/default.jpg">'+
'</td><td><b>'+ (sumN+1) +'</b> <a href="#" '+
'onclick="playVid('+sumN +', this); return false">'+
titSt +'</a></td></tr>';
stList += ss;
document.getElementById('foundText').innerHTML =
'<span style="color:green"><b>'+sum+'</b></span>';
document.getElementById('wantSpan').innerHTML = sumN + '';
sum++ ; sumN++ ;
if((sum == want)||(sum == resultCount)){
document.getElementById('foundText').innerHTML =
'<span style="color:red"><b>'+sum+'</b></span>';
document.getElementById('wantSpan').innerHTML =
'<span style="color:#6600FF">'+ sumN + '</span>';
document.getElementById('r1').innerHTML += stList;
sum = 0;
want = 150;
len = vid.length;
last = len - 1;
return;
}
} /* End of if(typeof ... */
} /* End of for(i=... */
document.getElementById('r1').innerHTML += stList;
x = want - sum;
if(x >= portion){
maxRes = portion;
}else{
maxRes = x;
}
searchVid(nextPageToken);
}); /* End of $.get( ... */
}
normalW = '980';
normalH = '551'
var player;
startvid = 'otPNwTrva0I';
var jj = 0;
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: normalW,
height:normalH,
videoId: startvid,
playerVars: { 'autoplay': 0, 'rel': 0, 'showinfo': 0, 'showsearch': 0, },
events: {
'onStateChange': onPlayerStateChange,
'onError': onPlayerError
}
});
}
function onPlayerError(error){
if ( error ){
nextVid();
}
}
function onPlayerStateChange(event) {
if (event.data == 0) {
nextVid();
return false;
}
}
function playVid(num){
jj=num;
showTit(num);
ide = vid[num];
player.loadVideoById(ide, "large");
ob = document.getElementById('list1')
ar = ob.getElementsByTagName('tr');
for(i=0;i<ar.length;i++){
if(ar[i].style.backgroundColor != "#EEEEEE"){
ar[i].style.backgroundColor = "#EEEEEE"
}
}
ar[num].style.backgroundColor = '#CCFF99';
}
function nextVid(){
len = vid.length;
if(len > 0){
last = len-1;
if(jj <= last){jj=jj+1};
if (jj > last){jj=0};
playVid(jj);
}else{
alert('At the openning, this page has only one video.\n\n'+
'You should search them more')
}
}
function showTit(k){
document.getElementById("vtitle").innerHTML = (k+1) +
'/'+ vid.length + ' : ' + tit[k];
}
function init(){
document.getElementById("vtitle").innerHTML = 'Pepito (Lisa del Bo)';
}
function readyTerm(term){
$("#searchtext1").val(term);
}
body{background-color:#999999; margin:0px;padding:0px;
font-family:Arial;font-size:10pt;}
td{border:1px solid gray;font-size:10pt;}
a{text-decoration:none;}
a:hover{color:green;}
input[type="button"], button{
background-color:#DDDDDD;cursor:pointer;padding:0px;
}
#vtitle{
width:980px;height:25px;color:white;background-color:#1B1B1B;
margin-top:-2px;overflow:hidden;padding-top:10px;
}
#header1{font-weight:bold;width:100%;height:24px;
background-color:#006699;padding:3px;position: fixed;left: 0px;top: 0px;}
#header1 td {border: none;}
<body onload="init()">
<div align="center">
<table id="header1" width=100% height="42px" style="margin-bottom:-7px;">
<tr>
<td width="50%" style="color:white;font-family:'Time New Roman';font-size:14pt">
<b><i> SEARCH AND PLAY CONTINUOUSLY</i></b>
</td>
<td width="50%" align="right">
<button type="button" onclick="player.pauseVideo();">|| Pause</button>
<button type="button" onclick="player.playVideo();">> Play</button>
<button type="button" onclick="nextVid();">>> Next</button>
</td>
</tr>
</table>
<div id='player' style="margin-top:37px"></div>
<div id="vtitle"></div><br>
<div id="menu" style="background-color:#99CCFF;padding:4px;width:100%">
<table ><tr style="font-size:10pt;">
<td style="background-color:white" style="border:1px gray solid">
<b>All: <span id="wantSpan"
style="font-size:12pt;font-style: italic">0</span></b>
<b><i>Found:</i>
<span id="foundText" style="font-size:12pt;font-style: italic;color:green">0
</span> </td></b>
<td style="border:1px gray solid;vertical-align:middle">
<b><i style="color:black;font-size:10pt">Search Text:</i></b> <input type="text"
value="Folli Michelangelo"
id="searchtext1" size="72" style="border-style:inset">
<button type="button" onclick="start(150)">S150</button>
<button type="button" onclick="start(300)">S300</button>
</td>
</tr></table>
</div><br>
<div id="tip" style =
"width:780px;height:15px;overflow:auto;background-color:white;text-align:left;padding:10px;line-height:160%">
Ricky King,
Paul Mauriat,
Richard Clayderman,
Folli Michelangelo
</div><br>
<b>SEARCH RESULTS</b>
<br><br>
<div id="list1"
style="width:800px;;height:300px;overflow:auto;background-color:white;text-align:left">
<table id="tableA" width="100%"><tbody id="r1">
</tbody></table>
</div><br>
</div> <!-- center -->

Categories