I request a username using a prompt within my index.html. My code looks like this:
<script>
// YOU DO NOT NEED TO EDIT THIS CODE
if (!/(&|\?)username=/.test(window.location.search)) {
var newSearch = window.location.search;
if (newSearch !== '' & newSearch !== '?') {
newSearch += '&';
}
var username = prompt('What is your name?') || 'anonymous';
console.log("From Index.html:" , username);
newSearch += 'username=' + (username);
window.location.search = newSearch;
}
</script>
I need to access this username within my app.js. I am sending a POST request to a server that requires the username as a property. For example:
//POST the message to the server
handleSubmit: function() {
var query = window.location.search;
var username = query.slice(10, query.length);
var room = $('#roomSelect').find(':selected').text();
var msg = {
username: username,
text: $('#message').val(),
roomname: room
};
app.send(msg);
console.log(msg);
app.renderMessage(msg);
}
Essentially, I want to prompt the user for their username in the index.html, but how do I access this variable from the app.js? Do I send it back to that file somehow?
You can try it to store in session variable and then access it from anywhere
Hope this will help you
Thanks!!!
Related
I am using an ajax function to verify user login and i am returning json on errors . i wanted to redirect to a particular url on successive login, but the i can only send json data from my function (eliminating the possibility of using url_for or redirect ) . so How do i dynamically get the root url so i can send it via json and then redirect via javascript.
heres my route`
def logincheck():
uname = request.form['username']
pwd = request.form['password']
if uname and pwd:
this = userlogin.query.filter_by(username = uname).first()
if this:
if this.password == pwd:
session['myid'] = this.uid
return jsonify(success = ?)
else:
return jsonify(p_error = 'Incorrect Password')
else:
return jsonify(u_error = 'Incorrect Username')
Thanks.
To get base url in javascript ,
var base_url = window.location.origin;
output : "http://yoururl.com"
var host = window.location.host;
output : yoururl.com
To redirect url in javascript ,
// redirect to another page
`window.location = "http://www.yoururl.com"`;
// it has similar behavior as an HTTP redirect
window.location.replace("http://yoururl.com");
// it has similar behavior as clicking on a link
window.location.href = "http://yoururl.com";
Hope this will help you.
I'm trying to write a tab url I get from a chrome extension to the Firebase database. However, FB throws an error, namely:
extensions::uncaught_exception_handler:8 Error in response to tabs.query: Error: Firebase.update failed: First argument contains an invalid key ([object MouseEvent]) in path /user-posts/[object MouseEvent]/-KM8uJZHiNsgtQbNh13I. Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"
The corresponding code in my popup.js:
function writeNewPost(uid) {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
var urlvar = tabs[0].url;
var postData = {
uid: uid,
url: urlvar
};
var newPostKey = firebase.database().ref().child('posts').push().key;
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
});
};
So does it complain because the url contains forbidden characters? It must be somehow possible to convert it in order to then write it to the database.
The function gets called through this:
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('clickme').addEventListener('click', writeNewPost);
});
The uid comes from the background.js, where the login is handled.
var uid = firebase.auth().currentUser.uid;
And it does return something.
What troubles me is that this same line in my popup.js returns null.
Well, the offending part is uid and has nothing to do with chrome.tabs API call - it comes from the outside (that you do not show).
It looks like you set writeNewPost as a handler for a mouse click - so it's getting passed a MouseEvent event object as its first parameter. That's where your error is.
It probably makes most sense to concentrate all your Firebase operations in the background page context - so instead of trying to call it directly, pass a Message to the background to perform the operation for you - because otherwise you have 2 instances of Firebase API and you need to do auth in both.
The problem was the uid is null during firebase.initializeApp() in the beginning of my popup.js. Calling firebase.auth().currentUser.uid in the function above returns the actual uid:
function writeNewPost() {
chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {
var urlvar = tabs[0].url;
var uid = firebase.auth().currentUser.uid; //This
var postData = {
uid: uid,
url: urlvar
};
var newPostKey = firebase.database().ref().child('posts').push().key;
var updates = {};
updates['/posts/' + newPostKey] = postData;
updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
});
};
I want to develop an app for Pebble. This app is going to tell you how long it takes from one place you set in options to another one taking in account traffic jams and stuff.
To achieve this I need to make a page that will return JSON. Pebble retrieves information using code like that:
var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;
ajax(
{
url: URL,
type: 'json'
},
function(data) {
// Success!
console.log('Successfully fetched weather data!');
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
I created a small page with a js script that gets needed information from Yandex API:
var route;
ymaps.ready(init);
var myMap;
function init(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var time = 0;
var home = getParameterByName("h");
var work = getParameterByName("w");
ymaps.route([home, work],{avoidTrafficJams: true}).then(
function (router) {
route=router;
time = ((route.getTime())/60).toFixed(2);
var info = new Object;
info["home"] = home;
info["work"] = work;
info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
JSON.stringify(info);
},
function (error) {
alert('Возникла ошибка: ' + error.message);
}
);
}
As you can see I can get a JSON string in the end. But how do I send it to clients when a request with right parameters is made?
I ended up using phantomjs and executing this js script on my php page.
I want to send json data through url to next html page. I checked it by emulator as I am working for mobile app, the url could not redirect to next page it is crashing at the moment what is the reason behind this. How can I parse it on next page .I am new to the jquery any idea? my json data contains result of two different sql queries in an array
$.ajax({
type : "POST",
datatype : "json",
url : "http://Localhost/phpBB3/check_pass.php?username="+ username + "&password="+ password+"&f=68",
success: function(data){
alert(data);
window.location.href="source/testmenu.html?varid=" + data +"&username=" + username +"&password=" + password;
}
});
This is the code on next page
$(document).ready(function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var arr = SearchString.split('&');
console.log(arr);
//Set session variables
var username = arr[1].split('=')[1];
var password = arr[2].split('=')[1];
document.getElementById('username').value = username;
document.getElementById('password').value = password;
)};
in your case in first page urlencode json
window.location.href="source/testmenu.html?varid=" + encodeURIComponent(data) +"&username=" + username +"&password=" + password;
and in next page
var data= arr[0].split('=')[1];
var recieved_json = $.parseJSON(data);
Then try this one:
var data = {
username: username,
password: password
};
$.ajax({
type: "POST",
url: "http://Localhost/phpBB3/check_pass.php",
params: $.param(data),
success: function(a) {
window.location.href = "source/testmenu.html?"
+ $.param(a) + "&" + $.param(data)
}
});
And this would be your code for the next page (the iterator is from Satpal's answer):
$(document).ready(function() {
var params = window.location.search;
var getURLParams = function(params) {
var hash;
var json = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
json[hash[0]] = hash[1];
}
return json;
}
params = getURLParams(params);
var username = params.username;
var password = params.password;
$('#username').val(username);
$('#password').val(password);
});
Though I agree with #Jai that sending username and password in url is not recommended.
Once you get the URL to load you'll need to run your data through some encoding and decoding. You might have the wrong path. If you want "http://Localhost/source/testmenu.html" make sure the first character is a "/".
Make sure your data object is encoded correctly.
// Encode data for querystring value.
var data = {
foo: "bar"
};
var data_str = JSON.stringify(data);
data_str = encodeURIComponent(data_str);
Decode and test your URL.
// Get data from querystring value.
// Get the query as an object with decoded values.
// Note that JSON values still need parsing.
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.data);
} catch (err) {
alert(err + "\nJSON=" + q.data);
}
Parameter should be html encode while navigating or requesting to the URL and decode at the receiving end. It may suspect potentially dangerous content which may leads to crash.
I have been working with indexedDB for a few hours now. I am attempting to create a registration and login system. Registration has worked well but the following code for login doesn't work. The error comes at the first alert after onsuccess. Can anyone help me identify where the error is? Thanks.
function getUser(e) {
var email = document.querySelector("#email").value;
var password = document.querySelector("#password").value;
console.log("About to login "+email);
var transaction = db.transaction(["users"]); //readonly
var objectStore = transaction.objectStore("users");
var request = objectStore.get(email);
request.onerror = function(e) {
alert("Unable to retrieve data from database!");
return;
};
request.onsuccess = function(e) {
alert(password " " + request.result.password);
if(password != request.result.password) {
alert("Could not log you in");
return;
}
console.log("You are logged in");
};
IndexedDb in javascript: I got a solution.
This solution is working for me. you need to use the index to read the data by calling the get() method.
Code snippet:
function(e) {
var email = document.querySelector("#email").value;
var password = document.querySelector("#password").value;
db = e.target.result;
var tx = db.transaction(["users"], "readonly");
var store = tx.objectStore("users");
// get the index from the Object Store
const index = store.index('email');
// query by indexes
var query = index.get(key);
query.onsuccess = function(e) {
console.log(query.result)
if(query.result)
{
if(password != query.result.password) {
alert("In-correct Credentials... Please check and try
again!!!");
}
else{
alert('success');
}
}
};
};
For reference you may visit: https://www.javascripttutorial.net/web-apis/javascript-indexeddb/