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 ;
}
Related
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.
Im trying to build a tow truck fare calculator, I found a script on here earlier, I modified it and it seems to be calculating fine, But now I need to add a drop down to it and calculate based on what selected.
Saying it quick, I need to know what we towing, if it is a car, the rate is 1.10 per mile made, If a van the rate is 1.30 per mile made and so on...
How do I take whats selected in drop down and calculate the fare?
I have litle php skills, so any comment appreciated.
<?php
session_start();
$rate = 1.10;
$fix = 75;
$callout = 65;
//}
?>
<!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 Dublin = new google.maps.LatLng(53.349805,-6.260310);
var mapOptions = {
center : Dublin,
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 (16>total){
var cost = <?php echo $fix; ?>;
}
else if (17<total && 700>total)
{
var cost = ((total * <?php echo $rate; ?>) + (<?php echo $callout; ?>));
}
var fare = 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: ["IE"]}
};
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>
Thanks
You could start from this...
<form action="process.php" method='post'>
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<input type="submit" />
</form>
Then in process.php $_POST['cars'] would be equal to whatever was submitted. Then just add another dropdown with something like <select name="prices"> and get $_POST['prices']
Closing image close2.jpg,close1.jpg is not working in Firefox while it is working in Google Chrome and in IE. URL is www.srfads.com -->home page-->finds ads in india--> click on change
my js file is
enter code here
function show(id,x,y)
{
var element = document.getElementById(id);
//var exit_element = document.getElementById(exit_id);
var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth;
if(width == 0)
{
width = 1280;
}
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight;
if(height == 0)
{
height = 786;
}
element.style.position = "absolute";
element.style.display = "block";
element.style.left = (document.documentElement.scrollLeft + (width - element.clientWidth)/2 + x) + 'px';
element.style.top = (document.documentElement.scrollTop + (height - element.clientHeight)/2 + y) + 'px';
var xmlhttpobject = new XMLHttpRequest();
xmlhttpobject.open("GET","sct.php",true);
xmlhttpobject.send();
xmlhttpobject.onreadystatechange = function ()
{
if(xmlhttpobject.readyState == 4 && xmlhttpobject.status == 200)
{
document.getElementById('shct').innerHTML = xmlhttpobject.responseText;
}
}
}
my php page is
change
<div id="showcity" style="display:none;border:8px solid rgb(120,120,120); border-radius:8px;">
<table style="background:white;">
<tr>
<td style="text-align: left;padding: 10px; width:300px; height:20px;border-bottom:1px solid;">Select a City</td>
<td style="text-align: right;padding: 10px; width:300px; height:20px;border-bottom:1px solid;">
<div id="clsdiv1" style="display: block;"><img src="img\close2.jpg" id="close1" onmouseover="show1()" /></div>
<div id="clsdiv2" style="display: none;"><img src="img\close1.jpg" id="close2" onmouseout="show2()" onclick="popupexit('showcity')" /></div>
</td>
</tr>
<tr>
<td colspan="2" style="height:200px;">
<div id="shct"></div>
</td>
</tr>
</table>
</div>
Will moving this line:
xmlhttpobject.send();
below this code:
xmlhttpobject.onreadystatechange = function ()
{
if(xmlhttpobject.readyState == 4 && xmlhttpobject.status == 200)
{
document.getElementById('shct').innerHTML = xmlhttpobject.responseText;
}
}
help?
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 -->
I am using the following code to edit a table of data on the fly for an admin area. It works well with only two columns, but when I add more I am not able to edit the data and have it save to mysql. Can someone show me how to add 5 more columns that will work. Here is a demo and where the code originates DEMO
<?php include('db.php'); ?>
<!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=iso-8859-1" />
<title>Live Table Edit</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".edit_tr").click(function() {
var ID = $(this).attr('id');
$("#first_" + ID).hide();
$("#last_" + ID).hide();
$("#first_input_" + ID).show();
$("#last_input_" + ID).show();
}).change(function() {
var ID = $(this).attr('id');
var first = $("#first_input_" + ID).val();
var last = $("#last_input_" + ID).val();
var dataString = 'id=' + ID + '&firstname=' + first + '&lastname=' + last;
$("#first_" + ID).html('<img src="load.gif" />');
if (first.length && last.length > 0) {
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$("#first_" + ID).html(first);
$("#last_" + ID).html(last);
}
});
}
else {
alert('Enter something.');
}
});
$(".editbox").mouseup(function() {
return false
});
$(document).mouseup(function() {
$(".editbox").hide();
$(".text").show();
});
});
</script>
<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
.editbox
{
display:none
}
td
{
padding:7px;
}
.editbox
{
font-size:14px;
width:270px;
background-color:#ffffcc;
border:solid 1px #000;
padding:4px;
}
.edit_tr:hover
{
background:url(edit.png) right no-repeat #80C8E5;
cursor:pointer;
}
th
{
font-weight:bold;
text-align:left;
padding:4px;
}
.head
{
background-color:#333;
color:#FFFFFF
}
</style>
</head>
<body>
<table width="100%">
<tr class="head">
<th>First Name</th><th>Last Name</th>
</tr>
<?php
$sql=mysql_query("select * from fullnames");
$i=1;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
if($i%2)
{
?>
<tr id="<?php echo $id; ?>" class="edit_tr">
<?php } else { ?>
<tr id="<?php echo $id; ?>" bgcolor="#f2f2f2" class="edit_tr">
<?php } ?>
<td width="50%" class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $firstname; ?></span>
<input type="text" value="<?php echo $firstname; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
</td>
<td width="50%" class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php echo $lastname; ?></span>
<input type="text" value="<?php echo $lastname; ?>" class="editbox" id="last_input_<?php echo $id; ?>"/>
</td>
</tr>
<?php
$i++;
}
?>
</table>
</body>
</html>
Here is the code for the ajax file table_edit_ajax.php
<?php
include("db.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$firstname=mysql_escape_String($_POST['firstname']);
$lastname=mysql_escape_String($_POST['lastname']);
$sql = "update fullnames set firstname='$firstname',lastname='$lastname' where id='$id'";
mysql_query($sql);
}
?>
edited code
<?php include('db.php'); ?>
<!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=iso-8859-1" />
<title>Live Table Edit</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".edit_tr").click(function() {
var ID = $(this).attr('id');
$("#first_" + ID).hide();
$("#last_" + ID).hide();
$("#othercolumn3_" + ID).hide();
$("#othercolumn4_" + ID).hide();
$("#othercolumn5_" + ID).hide();
$("#first_input_" + ID).show();
$("#last_input_" + ID).show();
$("#othercolumn3_input_" + ID).show();
$("#othercolumn4_input_" + ID).show();
$("#othercolumn5_input_" + ID).show();
}).change(function() {
var ID = $(this).attr('id');
var first = $("#first_input_" + ID).val();
var last = $("#last_input_" + ID).val();
var dataString = 'id=' + ID + '&firstname=' + first + '&lastname=' + last + '&othercolumn3=' + othercolumn3 + '&othercolumn4=' + othercolumn4 + '&othercolumn5=' + othercolumn5;
$("#first_" + ID).html('<img src="load.gif" />');
if (first.length && last.length && othercolumn3.length && othercolumn4.length && othercolumn5.length > 0) {
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$("#first_" + ID).html(first);
$("#last_" + ID).html(last);
$("#othercolumn3_" + ID).html(othercolumn3);
$("#othercolumn4_" + ID).html(othercolumn4);
$("#othercolumn5_" + ID).html(othercolumn5);
}
});
}
else {
alert('Enter something.');
}
});
$(".editbox").mouseup(function() {
return false
});
$(document).mouseup(function() {
$(".editbox").hide();
$(".text").show();
});
});
</script>
<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
.editbox
{
display:none
}
td
{
padding:7px;
}
.editbox
{
font-size:14px;
width:270px;
background-color:#ffffcc;
border:solid 1px #000;
padding:4px;
}
.edit_tr:hover
{
background:url(edit.png) right no-repeat #80C8E5;
cursor:pointer;
}
th
{
font-weight:bold;
text-align:left;
padding:4px;
}
.head
{
background-color:#333;
color:#FFFFFF
}
</style>
</head>
<body>
<table width="100%">
<tr class="head">
<th>1</th><th>2</th><th>3</th><th>4</th><th>5</th>
</tr>
<?php
$sql=mysql_query("select * from offers");
$i=1;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$firstname = $row['one'];
$lastname = $row['two'];
$othercolumn3 = $row['three'];
$othercolumn4 = $row['four'];
$othercolumn5 = $row['five'];
if($i%2)
{
?>
<tr id="<?php echo $id; ?>" class="edit_tr">
<?php } else { ?>
<tr id="<?php echo $id; ?>" bgcolor="#f2f2f2" class="edit_tr">
<?php } ?>
<td width="50%" class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $firstname; ?></span>
<input type="text" value="<?php echo $firstname; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
</td>
<td width="50%" class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php echo $lastname; ?></span>
<input type="text" value="<?php echo $lastname; ?>" class="editbox" id="last_input_<?php echo $id; ?>"/>
</td>
<td width="50%" class="edit_td">
<span id="othercolumn3_<?php echo $id; ?>" class="text"><?php echo $othercolumn3; ?></span>
<input type="text" value="<?php echo $othercolumn3; ?>" class="editbox" id="othercolumn3_input_<?php echo $id; ?>"/>
</td>
<td width="50%" class="edit_td">
<span id="othercolumn4_<?php echo $id; ?>" class="text"><?php echo $othercolumn4; ?></span>
<input type="text" value="<?php echo $othercolumn4; ?>" class="editbox" id="othercolumn4_input_<?php echo $id; ?>"/>
</td>
<td width="50%" class="edit_td">
<span id="othercolumn5_<?php echo $id; ?>" class="text"><?php echo $othercolumn5; ?></span>
<input type="text" value="<?php echo $othercolumn5; ?>" class="editbox" id="othercolumn5_input_<?php echo $id; ?>"/>
</td>
</tr>
<?php
$i++;
}
?>
</table>
</body>
</html>
ajax
<?php
include("db.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$firstname=mysql_escape_String($_POST['firstname']);
$lastname=mysql_escape_String($_POST['lastname']);
$othercolumn3 = mysql_escape_String($_POST['othercolumn3']);
$othercolumn4 = mysql_escape_String($_POST['othercolumn4']);
$othercolumn5 = mysql_escape_String($_POST['othercolumn5']);
$sql = "update offers set firstname='$firstname',lastname='$lastname', othercolumn3='$othercolumn3', othercolumn4='$othercolumn4, othercolumn5='$othercolumn5' where id='$id'";
mysql_query($sql);
}
?>
You mean this?
$firstname=mysql_escape_String($_POST['firstname']);
$lastname=mysql_escape_String($_POST['lastname']);
$othercolumn1 = mysql_escape_String($_POST['othercolumn1']);
...
$othercolumn5 = mysql_escape_String($_POST['othercolumn5']);
$sql = "update fullnames set firstname='$firstname',lastname='$lastname', othercolumn1='$othercolumn1', ..., othercolumn5='$othercolumn5' where id='$id'";
You'd have to create the appropriate input elements and add the required code to the jquery that's calling the script:
var first = $("#first_input_" + ID).val();
var last = $("#last_input_" + ID).val();
var othercolumn1 = $("#othercoumn1_input_" + ID).val();
...
var othercolumn5 = $("#othercoumn5_input_" + ID).val();
var dataString = 'id=' + ID + '&firstname=' + first + '&lastname=' + last + '&othercolumn1=' + othercolumn1 + ... + '&othercolumn5=' + othercolumn5;
$("#first_" + ID).html('<img src="load.gif" />');
if (first.length && last.length > 0) {
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html) {
$("#first_" + ID).html(first);
$("#last_" + ID).html(last);
$("#othercolumn1_" + ID).html(othercolumn1);
...
$("#othercolumn5_" + ID).html(othercolumn5);
}
But you should be able to sort things like this out for yourself. ;)
A better way is to add the html attribute "contenteditable" to the table cells to allow inline editing on clicking cell view
and then attach a function the onblur event to update the database using ajax.