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 -->
Related
I'm trying to make an addition (or subtraction if needed) to a php page with ajax.
What this code is supposed to do is add all the prices up and give me the correct sum with the live-edit-table.
if a user changes the value of price $price_total should change acordingly.
Even if a new row is added it should still give the new sum (displayed in $price_total and $final_price_total) with the new row included.
I have been trying to figure out how to do this but I can't figure out how.
$price_total and $final_price_total do not get saved into a database
this is the code that I have so far:
index.php
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<div id="live_data"></div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data(){
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
fetch_data();
function edit_data(id, text, column_name){
$.ajax({
url:"edit.php",
method:"POST",
data:{
id:id,
text:text,
column_name:column_name
},
dataType:"text",
success:function(data){
/*alert(data);*/
}
});
}
$(document).on('click', '#btn_add', function(){
/* this function would also add the prices to the table*/
var price = $('#price').text();
var final_price = $('#final_price').text();
if(price == ''){
alert("Enter Price");
return false;
}
if(final_price == ''){
alert("Enter Final Price");
return false;
}
$.ajax({
url:"insert.php",
method:"POST",
data:{price:price, final_price:final_price},
dataType:"text",
success:function(data){
alert(data);
fetch_data();
}
})
});
$(document).on('blur', '.price', function(){
var id = $(this).data("id1");
var price = $(this).text();
edit_data(id, price, "price");
/*I'm trying so that I can add the new input price with the old total to give the exact value*/
$total = parseFloat( price ) + parseFloat( $('#price_total').value );
$('#price_total').value = formatDecimal(total);
});
$(document).on('blur', '.final_price', function(){
var id = $(this).data("id2");
var final_price = $(this).text();
edit_data(id, final_price, "final_price");
});
});
select.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test_db");
$output = '';
$sql = "SELECT * FROM tbl_sample ORDER BY id DESC";
$result = mysqli_query($connect, $sql);
$output .= '
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="10%">Id</th>
<th width="40%">Price</th>
<th width="40%">Final Price</th>
<th width="10%">Delete</th>
</tr>';
if(mysqli_num_rows($result) > 0){
$final_price_total = 0;
$price_total = 0;
while($row = mysqli_fetch_array($result)){
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td class="price" data-id1="'.$row["id"].'" contenteditable>'.$row["price"].'</td>
<td class="final_price" data-id2="'.$row["id"].'" contenteditable>'.$row["final_price"].'</td>
<td><button type="button" name="delete_btn" data-id3="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">x</button></td>
</tr>
';
$final_price_total += $row["final_price"];
$price_total += $row["price"];
}
$output .= '
<tr>
<td></td>
<td class="price_total" id="price_total" name="price_total" value="'.$price_total.'" contenteditable>'.$price_total.'</td>
<td class="final_price_total" id="final_price_total" name="final_price_total" value="'.$final_price_total.'" contenteditable>'.$final_price_total.'</td>
<td></td>
</tr>
';
$output .= '
<tr>
<td></td>
<td id="price" contenteditable></td>
<td id="final_price" contenteditable></td>
<td><button type="button" name="btn_add" id="btn_add" class="btn btn-xs btn-success">+</button></td>
</tr>
';
}
else{
$output .= '<tr>
<td colspan="4">Data not Found</td>
</tr>';
}
$output .= '</table>
</div>';
echo $output;
?>
From the little discussion in the question comments, I've managed to spot this variable typo:
$total = parseFloat( price ) + parseFloat( $('#price_total').value );
$('#price_total').value = formatDecimal(total);
On the second line you are using total instead of $total.
If you check your browser's error console, you will see an error about undeclared variable total.
Edit: after further discussion, you wanted to know how to loop over the table in JavaScript and add up the total. Try this:
var newTotal = 0.0;
$('.price').each(function() {
newTotal += parseFloat($(this).text());
});
If you do this on your edit finding, you can then use the newTotal variable in the final_price field in place of where you are using the $total variable.
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.
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 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 ;
}
I made a form for showing users informations about some presentations. I used ajax cause it should be loaded into a div container and not reloading each time while changing the year.
This is my JavaScript:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: 'include/scripts/select_event.php',
type: 'POST',
data: data,
dataType: 'html',
success: function (select) {
$("#coffee_talk").html(select);
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
ORDER BY
Date ASC
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
/****************************/
/** Output der Tabelle
/****************************/
if ($getID[0] == '') {
echo 'Kein Eintrag vorhanden';
} else {
//Kopf
echo '<table id="table">
<thead>
<tr id="table_head">
<th>Nr.</th>
<th>Datum</th>
<th>Thema</th>
<th>Referent</th>
<th>Begin</th>
<th>Ort</th>
<th>Eintritt</th>
<th>Flyer</th>
<th>Bearbeiten</th>
</tr>
</thead>
<tbody>';
//Mittelteil
$j = 0;
for($i = 0; $i < count($getID); $i++) {
$j = $i + 1;
echo '<tr>
<td class="center">'.$j.'</td>
<td class="center">'.$getDate[$i].'</td>
<td class="center">'.$getTheme[$i].'</td>
<td class="center">'.$getContributer[$i].'</td>
<td class="center">'.$getBegin[$i].'</td>
<td class="center">'.$getPlace[$i].'</td>
<td class="center">'.$getEntrance[$i].'</td>';
if ($getFlyer[$i] == '') {
//Kein Bild vorhanden
echo '<td class="center">Kein Bild vorhanden</td>';
} else echo '<td class="center">'.$getFlyer[$i].'</td>';
echo '<td class="center">
<table id="icons">
<tr>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
</td>
<td>
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
</td>
</tr>
</table>
</td>
</tr>';
}
//Ende
echo '</tbody>
</table>';
}
}
}
As you can see my outpt is a table. I am using links to make an edit and delete function:
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="edit_event">
<img src="images/edit.png" />
</a>
and
<a href="#" data-event-id="'.$getID[$i].'" data-table="Coffee_talk" class="delete_event">
<img src="images/delete.png" />
</a>
This is my html with the placeholder div:
<div>
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
</div>
Now I want to use this JavaScript to do a delete and edit function:
$(".delete_event").click(function() {
alert('hallo');
currentUserID = $(this).data("event-id");
currentTable = $(this).data("table");
$( "#dialog_delete_event" ).dialog( "open" );
});
$( '#dialog_delete_event' ).dialog({
autoOpen: false,
resizable: false,
height: 170,
modal: true,
buttons: {
'Ja': function() {
document.location = "index.php?section=event_delete&id=" + currentUserID +"&table=" + currentTable;
$( this ).dialog( 'close' );
},
'Nein': function() {
$( this ).dialog( 'close' );
}
}
});
My problem is that the click_function (defined in the links) is not working. I Found out that the ajax form response is not written into the html code. Bet that this is the problem. What can I do to give the links a working click function?
im not sure due to your code's size but this:
$(".delete_event").click(function() {
should be
$(".delete_event").live("click",function() {
because you dynamically create html; the "live" works with that.
Like #Albit, not really sure what your question is, assuming the ajax is working correctly, and the results are visible on the screen, instead of using:
$(".delete_event").click(function() {
try
$(".delete_event").live("click", function() {
This means that elements that satisfy the selector after page load will still trigger an event.
i don't know if i undestood your problem correctly but just use the onclick event in the html tag of the anchor and you will be ok . if this is not the correct answer plese ignore me