Trying to figure out why this code doesn't work. When I console.log the userinfo, it comes back as ["", ""]. So, it's not collecting the username or password.
According to the documentation,
GET /users
returns a list of users.
{"users": ["alex", "bill", "charlie"]}
200 - Successful
GET /users/:name
Display a user.
200 - Successful
404 - User not found
What's going on?
/**
* Click event handler for submit button, return username and password
*/
function getInfo(){
var user = document.getElementById("username").value;
var username = user;
var pass = document.getElementById("password").value;
var password = pass;
return [username, password];
}
document.getElementById("submit").addEventListener("click", getInfo, false);
var userinfo = getInfo();
var username = userinfo[0];
var password = userinfo[1];
console.log(userinfo);
/**
* Get request for user's information, return user data, save as user.
* Check for matching password - if true open userprofile.html
* If false, show notice from index.html, reset user to empty
*/
function showGetResult( username )
{
var result = {};
var scriptUrl = "http://localhost:4567/main.rb";
$.ajax({
url: scriptUrl,
type: 'get/users[username]',
dataType: 'json',
async: false,
success: function(data) {
result.append(data);
}
});
return result;
}
var user = showGetResult(username);
console.log(user);
function passwordCheck(user, password)
{
if (user[2] === password){
window.open = "http://localhost:4567/userprofile/userprofile.html";
}
else {
document.getElementById("notice").style.display = "block";
user = {};
}
}
passwordCheck(user, password);
console.log("still working");
When you’re dealing with the DOM it’s important to execute your code only after the page is fully loaded. If you don’t, there’s a good chance the DOM won’t be created by the time your code executes. That's why you keep getting empty results or sometimes error. To overcome this, you need to ensure your script executes only when the page load is completed.
window.onload = init;
var username = "", password = "";
function init() {
document.getElementById("submit").addEventListener("click", getInfo, false);
}
function getInfo(){
username = document.getElementById("username").value;
password = document.getElementById("password").value;
}
I noticed you invoke the function getInfo() manually in your code. I don't know why you are doing that. By using the above code, your function will be invoked only when the submit button is clicked.
Related
The client will log in by sending a POST request to my server. My server will check this. If it works, I want to send the welcome page to the client but insert some data into it via a templating engine. I have everything but the redirect part figured out. This is what I have (I am using handlebars as a templating engine):
app.post("/loginAttempt",function(req, res)
{
var username = req.body.username;
var password = req.body.password;
//if credentials are incorrect, data is false
//otherwise, data is a html file as a string
var data = await checkCredentials(username,password);
if(data === false)
{
res.send("fail");
}
else
{
//not a real function, just using this to simplify code for this post
var temp = compileWithHandlebars("./front-end/welcome.html",{myData: data});
res.send(temp);
}
});
The problem with this is it sends a html file as a string instead of redirecting. This means the user sees no change in url, so they cannot hit the back button to go back to the login page.
I am guessing the temp is a string!
app.post("/loginAttempt",function(req, res)
{
var username = req.body.username;
var password = req.body.password;
//if credentials are incorrect, data is false
//otherwise, data is a html file as a string
var data = await checkCredentials(username,password);
if(data === false)
{
res.status(404).send("fail"); //<==
}
else
{
//not a real function, just using this to simplify code for this post
//var temp = compileWithHandlebars("./front-end/welcome.html",{myData: data});
res.redirect("./front-end/welcome.html",{data:myData});
}
});
Currently I have the user click submit and then a click event occurs where a token is created and a method is called. What I am trying to do is after the charge get a callback which says if it is successfully or not. If successful it will run router.go to the confirmation page. If it is not successful then it will let the user know the card has been declined. All the above I can code out except despite non stop tinkering, I can't seem to figure out how to pass the message back to the event.
Here is my server side method:
Meteor.methods({
'chargeCard': function(token,amount,email) {
var Stripe = StripeAPI('where the key info guys');
// get a sync version of our API async func
var stripeCustomersCreateSync=Meteor.wrapAsync(Stripe.customers.create,Stripe.customers);
// call the sync version of our API func with the parameters from the method call
var result=stripeCustomersCreateSync({
description: 'Woot! A new customer!',
card: token,
email: email
}, function(error,result) {
if(error) {
return error;
}
return 'Success';
});
return result;
}
});
and my Client side method:
Stripe.card.createToken({
number: $('#cc-number').val(),
cvc: $('#card-cvc').val(),
exp_month: expM,
exp_year: expY,
name: $('#fn').val(),
address_zip: $('#postCode').val()
}, stripeResponseHandler);
}
function stripeResponseHandler(status, response) {
var $form = $('form');
if (response.error) {
// Show the errors on the form
$form.find('.validation').text(response.error.message);
return false;
} else {
var token = response.id;
var amount = 15000;
var Payid = $('#pid').text();
var userEmail = Leaguemembers.findOne({_id: Payid}).Email;
Meteor.call('chargeCard', token, amount,userEmail, function (error, result) {
console.log(error,result); alert(result); alert(error);
}
);
}
};
Any help would be greatly appreciated.
EDIT:
I went back into the backend and I can see the errors being generated through console.log but still am unable to pass it back to where the call was made to display those errors to the user or pass them to the confirmation page. All I seem to get is undefined.
The meteor.call should look like this
Meteor.call('chargeCard',token,amount,username,function(err,result){
if(!err){
Router.go("theRoute") //if there is not error go to the route
}else{
console.log(err.reason) // show the error
}
})
I'm hoping this is just a simple fix due to me being a little dumb somewhere along the line. I'm executing my ASP.NET MVC login using AJAX. There is a "success" handler which returns a "true" value to the calling function which, in turn, load the home page.
The issue is that the "success" handler is executing BEFORE any value is returned - which means that nothing happens because the value is not "SUCCESS". I can confirm this by looking at the request in Firebug, the value returned is SUCCESS but nothing happens. If I apply a breakpoint to the end of the function and then continue execution it works just fine.
I have no idea what the issue is, I'd be very grateful for help or an explanation to what I'm doing wrong.
Thanks!
My JS Function:
function LogIn(UserName, Password) {
var Cont = true;
var ErrorString = "";
if (UserName == null || UserName == "") {
Cont = false;
ErrorString += "Username is Required.";
}
if (Password == null || Password == "") {
Cont = false;
ErrorString += "Password is Required.";
}
var result = false;
if (Cont) {
var LogInUrl = "/AJAX/LogIn?UserName=" + UserName + "&Password=" + Password;
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
result = true;
}
}
})
}
return result;
}
UPDATE: The function that calls the LogIn function:
$('#FormLogin').submit(function (e) {
e.preventDefault();
var UserName = $("#TxtLoginUsername").val();
var Password = $("#TxtLoginPassword").val();
var IsLoggedIn = LogIn(UserName, Password);
if (IsLoggedIn) {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
})
As I said, the function does it's job and logs me in, but the "success" handler seems to execute before the value is returned.
Change your ajax call to something like this:
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
}
});
There is no point in returning result from LogIn, it'll always be false. You need to put the code handling the returned value in the callback.
Another alternative, if you don't like the idea of your LogIn function being so closely coupled to DOM manipulation is to return the promise from your ajax call. So at the end of LogIn, you'd do something like this:
return $.ajax({
url: LogInUrl,
type:"GET"
}
});
And then when you call it, you'd do something like this:
LogIn(UserName, Password).then(function(data) {
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
});
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/
I am hoping someone can help me. I have the following function in FlashBuilder 4 using AS3:
protected function doIt():void
{
if (ExternalInterface.available) {
var retData:String;
retData = ExternalInterface.call("returndata");
if(retData != null) {
eidLbl.text = retData.toString();
} else {
eidLbl.text = "Returned Null";
}
} else {
eidLbl.text = "External Interface not available";
}
}
and the following javascript function it calls:
var fql_query = "some query format";
function returndata(){
return fql_query;
}
When I run these from my site everything works fine! The flash file calls the javascript function and returns "some query format" into the proper text field.
However if I change my flash function to be as follows:
protected function doIt():void
{
if (ExternalInterface.available) {
var retData:String;
retData = ExternalInterface.call("runFQL",uidLbl.text);
if(retData != null) {
eidLbl.text = retData.toString();
} else {
eidLbl.text = "Returned Null";
}
} else {
eidLbl.text = "External Interface not available";
}
}
and the following javascript function:
function runFQL(id){
var user_id = id;
var page_id = "**********"; // the page id that is actually there is valid
var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;
FB.api({
method: 'fql.query',
query: fql_query
},
function(response){
if (response[0]) {
var uid = response[0].uid;
window.alert(uid); //100001632043058
return uid;
} else {
window.alert("return 1000");
}
});
};
My problem is that when I run this one, it passes the id in, runs the query, and accurately pulls back the uid and displays it in the alert BUT (AND HERE IS MY PROBLEM) it won't pass it back to flash in the return. It comes back as null or undefined each time.
Can anyone tell me what I am missing. I have been scouring google for hours.
function(response){
if (response[0]) {
var uid = response[0].uid;
window.alert(uid); //100001632043058
return uid;
} else {
window.alert("return 1000");
}
});
Is called when the FB.api function completes not when you call runFQL. So runFQL runs through and returns undefined everytime.
What you can do is once the FB.api call completes call a function inside the flash app and pass the return value there. So basically do a ExternalInterface.addCallback in flash and call that function from javascript.
function runFQL(id){
var user_id = id;
var page_id = "**********"; // the page id that is actually there is valid
var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;
FB.api({
method: 'fql.query',
query: fql_query
},
function(response){
if (response[0]) {
var uid = response[0].uid;
window.alert(uid); //100001632043058
// needs ExternalInterface.addCallback("sendDataBack",handleData); in your
// as3 code
yourSwf.sendDataBack(uid);
} else {
window.alert("return 1000");
}
});
};
You have a very small work flow issue. In your JavaScript code you are calling FB api and then the function ends, in which case it will return a undefined since nothing is returned. But you are thinking that the nameless function is what does the return when actually it isn't even called yet because the API didn't even get a response.
What you need to do is change the following line of code.
return uid;
to
myHTMLFlashObject.someFunctionName(uid);
and in your flash project you need to add a function someFunctionName and add it as an ExternalInterface callback function.
Remember APIs are not asynchronous so you can expect the function runFQL to return undefined long before the API as sent a response.