cannot read property '0' of undefined 9 - firebase

This the text from where im getting the error. The the code is located after function sendData(). Where it starts with the:
var file = this.files[0];
I want to make where a button sends the files to the storage and not when it detects the state has been changed
var database = firebase.database();
var uploader = document.getElementById("uploader");
var fileButton = document.getElementById("fileButton").value;
var title = document.getElementById("title").value;
var description = document.getElementById("description").value;
var d = new Date();
var month = d.getMonth();
var day = d.getDay();
var hour = d.getHours();
var minute = d.getMinutes();
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
var currentUser = document.getElementById('currentUser').href = "#";
var currentUser = document.getElementById('currentUser').innerHTML = "Cuenta";
} else {
var currentUser = document.getElementById('currentUser').href = "/auth/login.html";
var currentUser = document.getElementById('currentUser').innerHTML = "Inicio De Sesión";
window.location.href = "/auth/login.html";
}
});
function sendData() {
var file = this.files[0];
var storage = firebase.storage().ref("News/" + file.name);
var task = storage.put(file);
task.on('state_changed', function(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function error(err) {
console.log("Error: " + err);
alert("Error");
}, function() {
firebase.storage().ref("News/").child(file.name).getDownloadURL().then(function(url) {
var title = document.getElementById("title").value;
var description = document.getElementById("description").value;
var ref = database.ref("News");
var data = {
imageURL: url,
Title: title,
Description: description,
Date: month + "/" + day + " " + h + ":" + minutes
}
ref.push(data);
});
});
};
HTML: Code
<div class="mainContainer">
<h1>Database</h1>
<input id="title" placeholder="Título" type="text">
<textarea id="description" placeholder="Description"></textarea>
<br>
<progress id="uploader" value="0" max="100">
0%
</progress>
<br>
<input type="file" value="upload" id="fileButton" accept=".png, .mp4, .mp3, .pdf">
<button onclick="sendData()">Enviar</button>
</div>

Probably this.files is undefined and you are trying to access the element at index 0.

Related

google maps directionsService giving wrong results

I am trying to get distance in miles and estimated time with googles directionsService. It sort of works but I know the results its giving me are incorrect. The distance and time are too short? I need results in driving mode. A sample of the code is :
HTML
<input id="s_lat" value="52.441334" />
<input id="s_lng" value="-1.654737" />
<input id="d_lat" value="52.450439" />
<input id="d_lng" value="-1.729660" />
JS
var n_start = s_lat + ',' + s_lng;
var n_end = d_lat + ',' + d_lng;
function getdistance() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin : n_start,
destination : n_end,
travelMode : google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true
};
directionsService.route(request, function(response, status) {
if ( status == google.maps.DirectionsStatus.OK ) {
alert (response.routes[0].legs[0].duration.value);
alert (response.routes[0].legs[0].distance.value);
}
else {
// oops, there's no route between these two locations
}
});
}
The result I get with the posted code is NOT_FOUND, I don't get a distance. A comma separated string is not a google.maps.LatLng or a google.maps.LatLngLiteral, it is treated as an address and geocoded before returning the results.
This:
var n_start = s_lat + ',' + s_lng;
var n_end = d_lat + ',' + d_lng;
Should be (google.maps.LatLngLiteral):
var n_start = {lat: parseFloat(s_lat.value), lng: parseFloat(s_lng.value)};
var n_end = {lat: parseFloat(d_lat.value), lng: parseFloat(d_lng.value)};
Or (google.maps.LatLng):
var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
Proof of concept fiddle
Code snippet:
function initMap() {
var n_start = new google.maps.LatLng(s_lat.value,s_lng.value);
var n_end = new google.maps.LatLng(d_lat.value,d_lng.value);
function getdistance() {
var directionsService = new google.maps.DirectionsService();
var request = {
origin: n_start,
destination: n_end,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
durationInTraffic: true
};
console.log(JSON.stringify(request));
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log("duration=" + response.routes[0].legs[0].duration.value + " seconds");
console.log("distance=" + response.routes[0].legs[0].distance.value + " meters");
document.getElementById('result').innerHTML = "distance=" + (response.routes[0].legs[0].distance.value / 1000).toFixed(2) + " km<br>duration=" + (response.routes[0].legs[0].duration.value / 60).toFixed(2) + " minutes";
new google.maps.DirectionsRenderer({
map: new google.maps.Map(document.getElementById('map')),
directions: response
})
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
getdistance();
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<input id="s_lat" value="52.441334" />
<input id="s_lng" value="-1.654737" />
<input id="d_lat" value="52.450439" />
<input id="d_lng" value="-1.729660" /><br>
<div id="result"></div>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

How to disable automatically signin after create new user in Firebase?

The admin can only add a new user. My problem is when I created a new user, it automatically signin that user then it signouts the admin.
FYI. I didn't use the Admin SDK. Firebase
My code:
var password = $('#row' + x + 'cell1').val();
var fname = $('#row' + x + 'cell2').val();
var email = teacherID + "#gmail.com";
console.log(email + password);
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
//Add to users table
var pushedUser = firebase.database().ref('users/' + user.uid).set({ role: "Teacher",
fullname: fname });
//Add name and default dp to the Authorization table
user.updateProfile({
displayName: fname,
photoURL: "default_dp",
});
var $rowFirst = $("table:first").find("tr:first");
var $rowNext = $('#tblCSVaccounts tr').eq(x);
//get all td's in row
var $tdsFirst = $rowFirst.find("td");
// loop all td
$.each($tdsFirst, function(i, el) {
//get value of each td
var txtEntity = $(this).find("input").val();
var $rowNext = $('#tblCSVaccounts tr').eq(x);
var $tdsNext = $rowNext.find("td:eq(" + i + ")");
$.each($tdsNext, function(i, el) {
//get value of each td
var txtValue = $(this).find("input").val();
//Update in database
const mySection = $('#sectionUpload').val();
var pushedRef = firebase.database().ref('Teachers/' + user.uid).update({ [txtEntity]: txtValue });
$('#alert-success').removeClass('hide');
});
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
});
you can use firebase.auth().onAuthStateChanged(...)
hope its help you, guy!

Use variables to access the right data in Firebase database using Vue.js

I'm building an app with Vue.js and Firebase as a backend. I'm retrieving data based on a URL parameter, for instance: http://localhost:8082/?link=fe3b096a8ab1f4d7146ba0ce7555336a85f0532272e748358ec81beb2b17e494
Then my code retrieves the values owneruid and tripuid thanks to this URL parameter. It allows me to get info from the user, such as userphotourl, username, tripphotourl, tripname, tripbegindate, tripenddate. So far it displays the values, so all good.
The variables owneruid and tripuid are stored, but because of the asynchronous, I included calls to functions that use this variables in my first .then(photosSnap => {, to run the rest of the code in a logical order.
Now I want to get all the photourl of all the photos of one trip (tripuid) of a user (owneruid). The database structure is like this :
How can I retrieve all the photourl and display them using v-for ?
My code :
import HelloWorld from './components/HelloWorld'
import Firebase from 'firebase'
let config = {
apiKey: "AIzaSyA9ap6pzsvkOv4tA2rgM6GKl2snKabzel4",
authDomain: "travelertest-e316f.firebaseapp.com",
databaseURL: "https://travelertest-e316f.firebaseio.com",
projectId: "travelertest-e316f",
storageBucket: "travelertest-e316f.appspot.com",
messagingSenderId: "605093453777"
}
let app = Firebase.initializeApp(config);
let database = app.database();
let photosRef = database.ref('trips');
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
let link = GetURLParameter('link');
console.log(link);
//var owneruid = 'bCbADd1qJqhoVbDg0QCDIlq5eMx1';
//var tripuid = '-Kiqtd3BxPX8WvpOTxsW';
var owneruid = '';
var tripuid = '';
database.ref(`links/${link}`).once('value').then(photosSnap => {
var obj = photosSnap.val();
owneruid = obj['owneruid'];
tripuid = obj['tripuid'];
console.log(owneruid);
console.log(tripuid);
getUserInfo();
getTripInfo();
getTripDate();
});
function getUserInfo() {
database.ref(`user_profiles/${owneruid}`).once('value').then(photosSnap => {
var obj = photosSnap.val();
var userphotourl = obj['photourl'];
var username = obj['name'];
$('.userphoto').attr('src', userphotourl);
$('.username').html(username);
});
}
function getTripInfo() {
database.ref(`trips/${owneruid}/trips/${tripuid}`).once('value').then(photosSnap => {
var obj = photosSnap.val();
var tripphotourl = obj['photourl'];
var tripname = obj['name'];
$('#tripcoverphoto').attr('src', tripphotourl);
$('.tripname').html(tripname);
});
}
function ConvertDate(DateInSeconds) {
var tripbegindateseconds = DateInSeconds;
var tripbegindatefull = new Date(0); // The 0 there is the key, which sets the date to the epoch
tripbegindatefull.setUTCSeconds(tripbegindateseconds);
var tripbeginmonth = tripbegindatefull.getUTCMonth() + 1; //months from 1-12
var tripbeginday = tripbegindatefull.getUTCDate();
var tripbeginyear = tripbegindatefull.getUTCFullYear();
tripbegindate = tripbeginday + "/" + tripbeginmonth + "/" + tripbeginyear;
return tripbegindate;
}
function getTripDate() {
database.ref(`trips/${owneruid}/trips/${tripuid}`).once('value').then(photosSnap => {
var obj = photosSnap.val();
var tripbegindate = ConvertDate(obj['begindate']);
var tripenddate = ConvertDate(obj['enddate']);
$('.tripbegindate').html(tripbegindate);
$('.tripenddate').html(tripenddate);
});
}
/*database.ref(`links/${link}`).once('value').then(photosSnap => {
var obj = photosSnap.val();
var owneruid = obj['owneruid'];
var tripuid = obj['tripuid'];
});
console.log(owneruid);
console.log(tripuid);*/
export default {
name: 'app',
firebase: {
photos: photosRef
}
}
<div id="app">
<div id="profile">
<img class="userphoto" src="" /><br/>
<font size="6" class="username"></font><br/>
<img id="tripcoverphoto" src="" alt="" /><br/>
<font size="8" class="tripname"></font><br/>
<font size="6" class="tripbegindate"></font><font size="6"> - </font><font size="6" class="tripenddate"></font>
</div>
<div id="photoslist" v-for="photo in photos">
<img id="image" height="400" width="400" src={{photo}}/>
</div>
</div>

Login with gmail api in my website in asp.net

I have to add the functionality of login with gmail account on my website. Users only with my domain should be validated and users trying to login with other domain should be redirected to google login page and shown an message. If user logs in successfully via gmail then he should also get logged in into membership table. How to do this in asp.net. Here is my code:
<script language="javascript" type="text/javascript">
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = '7480000038683-rhs9hdsc31uu2avuq8avlsed5i7hk.apps.googleusercontent.com';
var REDIRECT = 'http://localhost:0000/default.aspx?company=xyz';
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var HD = "ranosys.com";
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE + '&login_hint=' + LOGINHINT + '&hd='+ HD;
var acToken;
var tokenType;
var expiresIn;
var user;
var hd;
var loggedIn = false;
function login() {
var win = window.open(_url,"_self");
var pollTimer = window.setInterval(function () {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
}
catch (e) {
}
}, 500);
}
function validateToken(token) {
$.ajax(
{
url: VALIDURL + token,
data: null,
success: function (responseText) {
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
debugger;
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function (resp) {
user = resp;
var email = user.email;
alert(email);
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
namename = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\#&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null)
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
</script>
You need the lastest JQuery like this
Follow the last example here : http://www.gethugames.in/blog/2012/04/authentication-and-authorization-for-google-apis-in-javascript-popup-window-tutorial.html
This is my code working
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = '716569014051.apps.googleusercontent.com';
var REDIRECT = 'http://www.gethugames.in/proto/googleapi/oauth/'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
</script>
</head>
<body>
<a href='#' onClick='login();' id="loginText"'> Click here to login </a>
Click here to logout
<iframe name='myIFrame' id="myIFrame" style='display:none'></iframe>
<div id='uName'></div>
<img src='' id='imgHolder'/>
</body>
</html>

google maps directions: function is not correctly defined

i'm having a problem translating the already working directions script in v2 to v3.
the error is the tohere/fromhere function which is not correctly executed.
the marker is displayed correctly, after the first click the infowindow opens.
when i'm then clicking "tohere" or "fromhere" it throws error "tohere is not defined"...
any hints what i'm doing wrong?
jQuery(document).ready(function () {
if (jQuery('#map_canvas').length) {
initActive();
}
function initialize(lat, long,html) {
var latid = lat;
var longit = long;
var myLatlng = new google.maps.LatLng(latid, longit);
//var myLatlng = new google.maps.LatLng(51.512098,-0.137692);
var myOptions = {
zoom:17,
navigationControl:true,
mapTypeControl:false,
scaleControl:false,
scrollwheel:false,
disableDefaultUI:true,
disableDoubleClickZoom:true,
center:myLatlng,
mapTypeId:google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var styles = [
{
stylers:[
{ saturation:-100 }
]
}
];
map.setOptions({styles:styles});
var myLatLng = new google.maps.LatLng(latid, longit);
var marker = createMarker(map,myLatLng,html);
}
function initActive() {
var flat = jQuery('#map_canvas').data('coord-lat');
var flong = jQuery('#map_canvas').data('coord-lon');
var title = jQuery('#map_canvas').data('content');
initialize(flat, flong,title);
}
function createMarker(map, latlng,html) {
var marker = new google.maps.Marker({
position: latlng,
map: map
});
var infowindow = new google.maps.InfoWindow({ size: new google.maps.Size(150,50)});
marker.setIcon("mapIcons/marker_red.png");
var gmarkers = [];
var to_htmls = [];
var from_htmls = [];
var htmls = [];
var i = gmarkers.length;
// The info window version with the "to here" form open
to_htmls[i] = html + '<br>Directions: <b>To here<\/b> - <a href="javascript:fromhere(' + i + ')">From here<\/a>' +
'<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT">' +
'<input type="hidden" name="daddr" value="' + latlng.lat() + ',' + latlng.lng() +
// "(" + name + ")" +
'"/>';
// The info window version with the "to here" form open
from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here<\/a> - <b>From here<\/b>' +
'<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
'<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
'<INPUT value="Get Directions" TYPE="SUBMIT">' +
'<input type="hidden" name="saddr" value="' + latlng.lat() + ',' + latlng.lng() +
// "(" + name + ")" +
'"/>';
// The inactive version of the direction info
html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here<\/a> - <a href="javascript:fromhere('+i+')">From here<\/a>';
var contentString = html;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
gmarkers.push(marker);
htmls[i] = html;
}
// functions that open the directions forms
function tohere(i) {
infowindow.setContent(to_htmls[i]);
}
function fromhere(i) {
infowindow.setContent(from_htmls[i]);
}
}); //documentready close
All your code is local to the jQuery(document).ready function, so is not available in the global context where HTML click handlers run. Move the function declarations outside of that function.
Looks like your v2 code came from Mike Williams' v2 tutorial. This example of his "Getting Directions" map which I ported to v3, may help you.

Resources