I have a problem with my function. I want to make a login form validation by JSON data. My code works fine, but only when I put correct data just after refresh. For example, when I enter incorrect login/password I receive error, but after that when I type correct login/password nothing happens.
I'll be very grateful if you can help. Here is my js code:
//JSON validation
function validation(username, password){
var alert = document.getElementById("invalid-data");
data = JSON.parse(data);
for (var i=0; i < data.length; i++) {
if (username == data[i].login && password == data[i].password) {
window.open("panel.html", "_self");
} else {
alert.style.display = "block";
}
}
}
//Form validation
function getLoginInfo() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
validation(username, password);
}
var button = document.getElementById("login-button");
button.addEventListener("click", getLoginInfo);
i hope your problem is data = JSON.parse(data); because when first time you get parse data you put it into data again and it cause problem in your next data json parsing. so i think your problem would be solve if you put your parsed data into different variable like code bellow:
//JSON validation
function validation(username, password){
var alert = document.getElementById("invalid-data");
var parsed_data = JSON.parse(data);
for (var i=0; i < parsed_data.length; i++) {
if (username == parsed_data[i].login && password == parsed_data[i].password) {
window.open("panel.html", "_self");
} else {
alert.style.display = "block";
}
}
}
//Form validation
function getLoginInfo() {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
validation(username, password);
}
var button = document.getElementById("login-button");
button.addEventListener("click", getLoginInfo);
So, problem of this function was that
data = JSON.parse(data);
was inside a function. I made it global and everything works fine.
Related
After the submit button for my form is clicked the function formvalidtion() is executed from a javascript file, below.
function formValidation() {
var fname = document.getElementById('firstName').value;
var lname = document.getElementById('lastName').value;
var pnumber = document.getElementById('phoneNumber').value;
var email = document.getElementById('e-mail').value;
return FirstName(fname) && LastName(lname) && PhoneNumber(pnumber) && Email(email) && thankyou();
return false;
}
Example of individual validation.
function FirstName(fname) {
var message = document.getElementsByClassName("error-message");
var letters = /^[A-Za-z]+$/;
if ( fname =="" || fname.match(letters)) {
text="";
message[0].innerHTML = text;
return true;
}
else {
text="First name should contain only letters";
message[0].innerHTML = text;
return false;
}
}
As noted in the function formvalidtion() I have the function thankyou() referenced which is below.
function thankyou() {
if (formValidation() === true){
alert("Thank you for subscribing!");
}
}
The rest of the validation functions are working not this though, the acknowledgement alert is not appearing. TIA!
You send your function into a recursive pattern without a base case by allowing two functions call themselves(formValidation and thankYou). You can fix this by removing the conditional in the thankYou function
function thankyou() {
alert("Thank you for subscribing!");
}
So I've been trying to do this for more than a day now. I'm getting a few user inputs through a form (ex - a name of a car), then I search through a JSON file to see whether its available. After this I'm trying to send the results of the search to a results page. I've been trying to use a cookie for this process. However there is a problem that I can't figure out. Following is my code,
This is getting input and searching:
function search() {
var name = $("input[name=carName]").val();
var cars = new Array();
$.getJSON("properties.json", function (data) {
$(data.cars).each(function (index, value) {
if (value.name == name) {
cars.push(value);
}
});
if (cars.length > 0) {
send(cars);
} else {
// do some handling
}
});
function send(cars) {
var str = JSON.stringify(cars);
Cookies.set("carResults", str);
window.location.replace("result.html");
}
This is the script from result.html
<script>
$(document).ready(function () {
var temp = Cookies.get("carResults");
var cars = JSON.parse(temp);
if(results!=null) {
for (var i = 0; i < results.length; i++) {
var temp1 = "Found a " + cars[i].name;
$("#resultArea").append(temp1);
}
} else {
$("#resultArea").append("Nothing to show");
}
});
</script>
PS. I'm using a javascript library called cookie.js for creating cookies
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.
I have this particular problem, where I need to validate the data before it is saved via an ajax call. save_ass_rub function is called when user navigates to a different URL.
In my application, I have a custom Window and user is allowed to input data. I am able to capture all the data in this step: var data = $('form').serialize(true);. But I need to loop through this and check if data for some specific elements is empty or not. I can't do it when the user is in the custom window. The Custom window is optional for the user. All I want is to alert the user in case he has left the elements blank before the data is submitted.
We are using Prototype.js and ajax .
<script>
function save_ass_rub() {
var url = 'xxxx';
var data = $('form').serialize(true);
var result;
new Ajax.Request( url, {
method: 'post',
parameters: data,
asynchronous: false, // suspends JS until request done
onSuccess: function (response) {
var responseText = response.responseText || '';
if (responseText.length > 0) {
result = eval('(' + responseText + ')');
}
}
});
if (result && result.success) {
return;
}
else {
var error = 'Your_changes_could_not_be_saved_period';
if (window.opener) { // ie undocked
//Show alert in the main window
window.opener.alert(error);
return;
}
return error;
}
}
// Set up auto save of rubric when window is closed
Event.observe(window, 'unload', function() {
return save_ass_rub();
});
</script>
Can some thing like this be done?
After Line
var data = $('form').serialize(true);
var split_data = data.split("&");
for (i = 0; i < split_data.length; i++) {
var elem = split_data[i];
var split_elem = elem.split('=');
if( split_elem[0].search(/key/) && split_elem[0] == '' ){
console.log( split_elem );
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
}
Instead of using the serialized form string, I would use the form itself to do the validation. if $('form') is your form element then create a separate function that checks the form element so its compartmentalized.
function checkform(form)
{
var emptytexts = form.down('input[type="text"]').filter(function(input){
if(input.value.length == 0)
{
return true;
}
});
if(emptytexts.length > 0)
{
return false;
}
return true;
}
and in the save_ass_rub() function
//..snip
if(checkform($('form') == false)
{
var error = 'Not all the elements are inputted';
window.opener.alert(error);
return;
}
var data = $('form').serialize(true);
var result;
I only added text inputs in the checkform() function you can the rest of the input types and any other weird handling you would like to that function. As long as it returns false the error will be displayed and the js will stop otherwise it will continue
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/