How to display firebase auth/wrong-password as window alert? - javascript

I'm trying to add an error checker whenever I place an invalid email and/or password. What I want to happen if I provide an invalid email or password the page should provide a window alert about the error.
My .js code
(function(){//initialize the firebase app
var config = {
assume there are credentials here
};
firebase.initializeApp(config);
var auth = null;
var loginBtn= document.getElementById('btnLogin');
firebase.auth.Auth.Persistence.SESSION;
//Login
loginBtn.addEventListener('click', e => {
e.preventDefault();
if( $('#email').val() != '' && $('#password').val() != '' ){
//login the user
var data = {
email: $('#email').val(),
password: $('#password').val()
};
firebase.auth().signInWithEmailAndPassword(data.email, data.password)
.then(function(authData) {
auth = authData;
})
.catch(function(error) {
console.log("Login Failed!", error);
window.alert("Login Failed!", error);
});
}
});
})();
My issue is that the window alert does not execute. I already tried an else statement it won't work as well.
html code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login | DIABEATIS by Team Buendia</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="images/icons/diabeatis.jpg" />
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,200" rel="stylesheet" />
<link href="https://use.fontawesome.com/releases/v5.0.6/css/all.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
<script src='https://cdn.firebase.com/js/client/2.2.1/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-app.js" ></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-storage.js"></script>
</head>
<body>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100 p-t-30 p-b-20">
<form id="loginForm" method="POST">
<img src="images/icons/diabeatis.jpg" width="70%" style="margin: 0px auto 20px;display: block;" alt="AVATAR">
<span class="login100-form-title p-b-40">
<font face="Montserrat">By Team Buendia</font>
</span>
<div class="wrap-input100 validate-input m-t-25 m-b-35" data-validate="Enter username">
<font face="Montserrat">Email</font>
<input class="input100" type="text" name="loginEmail" style="font-family:Montserrat;" id="email">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input m-b-50" data-validate="Enter password" >
<font face="Montserrat">Password</font>
<input class="input100" type="password" name="loginPassword" id="password">
<span class="focus-input100"></span>
</div>
<button type="submit" class="login100-form-btn" style="background-color:blue; font-family:Montserrat; cursor:pointer; font-weight:bold" id="btnLogin">Login</button>
<ul class="login-more p-t-40">
<font face="Montserrat">Don't have an account?</font>
<li class="m-b-8">
<a href="signup.html" class="txt2" style="color:#01703D">
<font face="Montserrat">Create Account</font>
</a>
</li>
<font face="Montserrat">Are you a doctor? Login here</font>
<li class="m-b-8">
<a href="" class="txt2" style="color:#01703D">
<font face="Montserrat">DIABEATIS for Doctors</font>
</a>
</li>
<font face="Montserrat">By Logging in you agree to our Terms & Conditions, as well as, our privacy and policy</font>
<br>
<li class="m-b-8">
<a href="toc.html" class="txt2" style="color:#01703D">
<font face="Montserrat">Terms & Conditions</font>
</a>
</li>
<li class="m-b-8">
<a href="privacypolicy.html" class="txt2" style="color:#01703D">
<font face="Montserrat">Privacy and Policy</font>
</a>
</li>
</ul>
</form>
</div>
</div>
</div>
<script src="signin.js"></script>
<script>
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location.href = "patientDashboard.html";
console.log(user);
}
else{
console.log('no user present');
}
});
</script>
</body>
</html>

It is probably because you assign the submit type to your button and the POST method to your form. Therefore your form is probably submitted before the signInWithEmailAndPassword() Firebase method is triggered and/or the Promise it returns is resolved.
Changing the type to button, as follows, should do the trick:
<button type="button" class="login100-form-btn" style="background-color:blue; font-family:Montserrat; cursor:pointer; font-weight:bold" id="btnLogin">Login</button>
See the W3 specification for more detail.

Related

html & javascript enter button redirects to error page - otherwise duplicates text to chat (only when enter is pressed)

Whenever I click on the enter button, it seems the page either shows me
Bad Request
Did not attempt to load JSON data because the request Content-Type was not 'application/json'.
or rarely if enter is pressed it creates duplicates each chat by itself and adds it to the div
I have removed the key event of enter but for some odd reason the enter function still works, I presume this is due to bootstrap but im not too certain.
<!DOCTYPE html>
<html lang="en" style="height: 500px">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lexend" rel="stylesheet" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/stylesheet.css') }}">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://www.unpkg.com/spltjs#1.1.0"></script>
<script src="https://releases.jquery.com/git/jquery-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeit/5.0.2/typeit.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<!-- Navbar content -->
<button type="button" class="btn btn-light" style="height:34px">click me</button>
<p style="color:white; font-family: Lexend;font-size: 15px;font-weight: 400;text-align: center;">AI for a healthier you</p>
<button type="button" class="btn btn-light" style="height:34px">click me</button>
</nav>
<br>
<center>
<div class="container" style="background-color:white ; border-radius: 20px;height:80%;-webkit-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);-moz-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);">
<p style="color:black" id="hello"></p>
<form method="post">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Type here...." aria-label="Recipient's username" aria-describedby="basic-addon2" name="userid" id="textinput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" value="hello world" id="button">Submit</button>
</form>
</div>
</div>
</div>
</center>
<script>
document.getElementById("button").addEventListener("click", insertText);
// CREATES A DIV AND SENDS THE USERS TEXT
function insertText() {
let div = document.createElement("div");
let usertext = document.getElementById('textinput').value;
const usertext2 = 'Patient: ' + usertext;
let text = document.createTextNode(usertext2);
div.appendChild(text);
document.getElementById("hello").appendChild(div);
/////////////// submit JSON TO APP
var json_entry = usertext
fetch('/dashboard', {
method: 'POST',
body: JSON.stringify({
user_text: json_entry
}),
headers: {
'Content-Type': 'application/json'
}
});
let apiData;
fetch('/dashboard/api').then((response) => response.json()).then((data) => {
apiData = data;
let div = document.createElement('div');
let robot_reply = document.createTextNode(apiData);
div.appendChild(robot_reply);
document.getElementById("hello").appendChild(div);
});
////// ENTER BUTTON ////
///////////////////////
/////////////////////// allows the ability to hit the enter button
var input = document.getElementById("textinput");
}
</script>
</div>
</div>
</body>
</html>
When you hit enter, it triggers the submit event on the <form>, which will cause a page refresh. This is basically baked in browser functionality. Any enter keypress in a field inside a <form> tag, causes a form submission. If that form submission is not handled, it will attempt to POST the form to the current URL.
You need to attach everything to the submit event on the <form>, not the button click. And you also need to call e.preventDefault to prevent the browsers default form action handling.
Additionally, you need type="submit" on the button so the click on that button also submits the form.
Using form submit event is also better for accessibility. It means users can press enter in a field or click the button, and it will be handled.
<!DOCTYPE html>
<html lang="en" style="height: 500px">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Bootstrap</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Lexend" rel="stylesheet" />
<link rel="stylesheet" href="{{ url_for('static', filename='css/stylesheet.css') }}">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://www.unpkg.com/spltjs#1.1.0"></script>
<script src="https://releases.jquery.com/git/jquery-git.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeit/5.0.2/typeit.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<!-- Navbar content -->
<button type="button" class="btn btn-light" style="height:34px">click me</button>
<p style="color:white; font-family: Lexend;font-size: 15px;font-weight: 400;text-align: center;">AI for a healthier you</p>
<button type="button" class="btn btn-light" style="height:34px">click me</button>
</nav>
<br>
<center>
<div class="container" style="background-color:white ; border-radius: 20px;height:80%;-webkit-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);-moz-box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);box-shadow: 10px 10px 79px -7px rgba(0,0,0,0.22);">
<p style="color:black" id="hello"></p>
<form method="post" id="form">
<div class="input-group mb-3">
<input type="text" class="form-control" placeholder="Type here...." aria-label="Recipient's username" aria-describedby="basic-addon2" name="userid" id="textinput">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="submit" value="hello world" id="button">Submit</button>
</form>
</div>
</div>
</div>
</center>
<script>
document.getElementById("form").addEventListener("submit", insertText);
// CREATES A DIV AND SENDS THE USERS TEXT
function insertText(e) {
e.preventDefault();
let div = document.createElement("div");
let usertext = document.getElementById('textinput').value;
const usertext2 = 'Patient: ' + usertext;
let text = document.createTextNode(usertext2);
div.appendChild(text);
document.getElementById("hello").appendChild(div);
/////////////// submit JSON TO APP
var json_entry = usertext
fetch('/dashboard', {
method: 'POST',
body: JSON.stringify({
user_text: json_entry
}),
headers: {
'Content-Type': 'application/json'
}
});
let apiData;
fetch('/dashboard/api').then((response) => response.json()).then((data) => {
apiData = data;
let div = document.createElement('div');
let robot_reply = document.createTextNode(apiData);
div.appendChild(robot_reply);
document.getElementById("hello").appendChild(div);
});
////// ENTER BUTTON ////
///////////////////////
/////////////////////// allows the ability to hit the enter button
var input = document.getElementById("textinput");
}
</script>
</div>
</div>
</body>
</html>

access table from PHP database in Javascript

I have created a login page that allows you to log in using username and password. However, it is currently so that you are always redirected to the "profile" page and there is then checked by PHP whether the login data are correct, because the data are on the DB.
Therefore I have the idea with a validate function directly on the loginpage to check if the data is correct and then I just create a session.
Does anyone have an idea how I can do this?
Here is the code:
<?php session_start();?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css"> <!-- maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js or bootstrap.js-->
<script src="jquery.js"></script> <!-- //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
</div>
<!-- Login Form -->
<form action="searchpage.php" method="post" onsubmit="validateForm(event);">
<input type="text" id="login" class="fadeIn second" name="username" placeholder="username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" style="color:red" id="warning"></a>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
var input_username = document.getElementById("login");
var input_password = document.getElementById("password");
if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
event.preventDefault();
document.getElementById("warning").innerHTML = "Fill empty fields!";
}
else {
return true;
}
}
</script>
with this I reach the DB:
$pdo = new PDO('mysql:host=localhost;dbname=ausleihe', 'root', '');
and that is the SELECT:
$login_session = "SELECT * FROM login WHERE username = '".$hereshouldbetheusernamefromform."' AND password = '".herethepasswordfromform."'";
If you need more code or have questions, ask me!
Thx
Client-side JavaScript cannot directly access a Host-side PHP program except through AJAX calls. Only the Host-side software has access to Host-side databases.

Why is login function in code not called?

I added a breakpoint at login function. When I submit the form, the login function should be called; but it's not called. And when I log in, the page doesn't redirect to window.location. I want the page to be redirected if the login credentials are the same as the one in local storage. I know we shouldn't validate your code client side. But for now, let's just ignore that.
var db = window.localStorage;
function signUp() {
var signupFormDt = document.querySelector('#signup-form');
var email = signupFormDt.querySelector('input[name="email"]');
var password = signupFormDt.querySelector('input[name="password"]');
var userName = signupFormDt.querySelector('input[name="name"]');
db.setItem(userName.name, userName.value);
db.setItem(email.name, email.value);
db.setItem(password.name, password.value);
}
function login() {
var loginFormDt = document.querySelector('#login-form');
var logEmail = loginFormDt.querySelector('input[type="email"]');
var logPass = loginFormDt.querySelector('input[type="password"]');
if (db.email == logEmail.value && db.password == logPass.value) {
window.location = 'http://www.google.com';
} else {
window.location = "http://www.google.com";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<!--Link to StyleSheet-->
<link rel="stylesheet" href="../css/style.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
</head>
<body>
<header>
<div class="container">
<h1>
</h1>
<nav>
<ul class="clearfix">
<li>
<a href="#">
<h4>Home</h4>
</a>
</li>
<li>
<a href="../html/about.html">
<h4>About</h4>
</a>
</li>
<li>
<a href="#">
<h4>Contact</h4>
</a>
</li>
<li>
<a href="#">
<h4 id="social">Social</h4>
<div class="arrow"></div>
<ul>
<li>Twitter</li>
<li>Facebook</li>
<li>Instagram</li>
<li>Snapchat</li>
<li>Tumblr</li>
</ul>
</a>
</li>
</ul>
<!-- end of ul of main nav-->
</nav>
<!--end of nav-->
</div>
<!--end of container-->
</header>
<main>
<section>
<h3>login Page</h3>
<div id="login">
<p>Myselfie Tech</p>
<form method="Post" id="login-form">
<p>
<input type="email" name="email" id="email" placeholder="email" required>
</p>
<p>
<input type="password" name="password" id="password" placeholder="password" required>
</p>
<p>
<button type="submit" onsubmit="login()">Submit Query</button>
</p>
<p>
<button onclick="window.location='../html/index.html'">Back</button>
</p>
</form>
</div>
</section>
</main>
<footer>
<p>
<center><small>©Copyright 2017 programmers inc.</small></center>
</p>
</footer>
<!--Link to Javascript-->
<script src="../javascript/scripts1.js"></script>
</body>
</html>
A button element does not have an onsubmit attribute. You should put that attribute on the form tag for it to work. Also make sure that the form submission is cancelled, since you want to control the navigation differently, with window.location:
Add return:
<form onsubmit="return login();">
Add return false, and .href after location:
function login() {
var loginFormDt = document.querySelector('#login-form');
var logEmail = loginFormDt.querySelector('input[type="email"]');
var logPass = loginFormDt.querySelector('input[type="password"]');
if (db.email == logEmail.value && db.password == logPass.value) {
window.location.href = 'http://www.google.com';
} else {
window.location.href = "http://www.google.com";
}
return false; // <------
}
Try using input tag instead of button for submit
something like
<input id="clickMe" type="button" value="Submit Query" onclick="login()" />

Contents of an iframe are not showing (UncaughtType Error)

Good day! I am using iframe and instead of an src to another page for its contents, I used the iframe's id to call a Javascript action but nothing shows. Here is my code:
#(title: Html, nav: String = "")(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>Impact Analysis Knowledge Management Tool</title>
<style>
.menu {
width:25%;
height:100%;
}
.mainContent {
width:75%;
height:100%;
}
</style>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/bootstrap.css")">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<link href='#routes.Assets.at("stylesheets/css/ui-lightness/jquery-ui-1.10.4.css")' rel="stylesheet">
<script src='#routes.Assets.at("javascripts/jquery-ui-1.10.4.js")'></script>
<script type="text/javascript">
var doc = document.getElementById('frame').contentWindow.document;
doc.open();
doc.write('<div class="container"> <div class="content"> <div class="row"> <div class="span14"> #content </div> </div> </div> </div>');
doc.close();
</script>
</head>
<body>
<div class="topbar">
<div class="fill">
<div class="container">
<a class="brand" href="#routes.Application.index()">Home</a>
<ul class="nav">
<li class="#("active".when(nav == "add tag"))">
Add Tag
</li>
<li class="#("active".when(nav == "view edit"))">
View/Edit Tag
</li>
<li class="#("active".when(nav == "log"))">
Log Information
</li>
<li class="#("active".when(nav == "map"))">
Web Map
</li>
</ul>
<p align="right"> Log-out </p>
</div>
</div>
</div>
<iframe class="menu" src="#routes.Tags.map(false)" ></iframe>
<iframe id="frame" class="mainContent" src="about:blank" ></iframe>
</body>
</html>
The left iframe has no problem but the other side (where there is no src) is empty. I checked the console and it says Uncaught TypeError: Cannot read property 'contentWindow' of null. Please help me figure this out. Thanks a lot.
EDIT
This is the page-source.
<link rel="stylesheet" href="/assets/stylesheets/jquery-ui.css">
<script src="/assets/javascripts/jquery-1.10.2.js"></script>
<script src="/assets/javascripts/jquery-ui-1.10.4.js"></script>
<script src='/assets/javascripts/jquery-1.7.1.min.js' type="text/javascript"></script>
<script>
$(function() {
var availableTags = ["rule 14","rule 15","rule 13","domestic route","block time","working crew","daily schedule","rule 1"];
var scntDiv = $('#addMore');
var i = $('#addMore p').size();
$('#addRT').live('click', function() {
$('<p>'+
'<input id="tags'+i+'" type="text" name="relatedTags.tag.name" placeholder="Name" required /> '+
'<textarea name="relatedTags.relatedNotes" placeholder="Notes"></textarea> '+
'<select name="relatedTags.relationship"> <option value="parent"> parent </option>'+
'<option value="child"> child </option>'+
'<option value="peer"> peer </option>'+
'</select> '+
'Remove</p>').appendTo(scntDiv);
$( "#tags"+i ).autocomplete({
source: availableTags
});
i++;
return false;
});
$('#remRT').live('click', function() {
if( i > 0 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
function checkDuplicates() {
if ( $.trim( $('#name').val() ) == '' ) {
alert('Invalid name.');
return false;
}
else {
var availableTags = ["rule 14","rule 15","rule 13","domestic route","block time","working crew","daily schedule","rule 1"];
var input = document.getElementById('name').value;
input = input.replace(/\s+/g,' ').trim().toLowerCase();
var found = $.inArray(input, availableTags);
if(found != -1) {
alert("Tag already exists.");
return false;
} else { //does not contain the value
var k = $('#addMore p').size();
for (var i=0; i<k; i++) {
for (var j=0; j<k; j++) {
if (i!=j){
if (document.getElementById('tags'+i).value==document.getElementById('tags'+j).value &&
document.getElementById('tags'+i).value!="" && document.getElementById('tags'+j).value!="") {
alert("Duplicate entries found.");
document.getElementById('tags'+i).select();
return false;
}
}
}
}
return true;
}
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<title>Impact Analysis Knowledge Management Tool</title>
<style>
.menu {
float:left;
width:20%;
height:100%;
}
.mainContent {
float:left;
width:79%;
height:100%;
}
</style>
<link rel="stylesheet" media="screen" href="/assets/stylesheets/bootstrap.css">
<link rel="stylesheet" media="screen" href="/assets/stylesheets/main.css">
<link rel="shortcut icon" type="image/png" href="/assets/images/favicon.png">
<link href='/assets/stylesheets/css/ui-lightness/jquery-ui-1.10.4.css' rel="stylesheet">
<script src='/assets/javascripts/jquery-ui-1.10.4.js'></script>
</head>
<body>
<div class="topbar">
<div class="fill">
<div class="container">
<a class="brand" href="/index">Home</a>
<ul class="nav">
<li class="active">
Add Tag
</li>
<li class="">
View/Edit Tag
</li>
<li class="">
Log Information
</li>
<li class="">
Web Map
</li>
</ul>
<p align="right"> Log-out </p>
</div>
</div>
</div>
<iframe class="menu" src="/map?editable=false" ></iframe>
<iframe id="frame" class="mainContent" src="about:blank"></iframe>
<script type="text/javascript">
$(function(){
var doc = document.getElementById('frame').contentWindow.document;
doc.open();
doc.write("<div class='container'> <div class='content'> <div class='row'> <div class='span14'>
<p align="right"> Logged in as: <b>user1</b> </p>
<h1> Add Tag </h1>
<form action="/addTag" method="POST" id="form" onsubmit="return checkDuplicates(this);">
<fieldset>
<legend>Add Tag</legend>
<div class="clearfix " id="name_field">
<label for="name">Name</label>
<div class="input">
<input type="text" id="name" name="name" value="" >
<span class="help-inline"></span>
<span class="help-block">Maximum length: 100, Required</span>
</div>
</div>
<div class="clearfix " id="notes_field">
<label for="notes">Impact Analysis Notes</label>
<div class="input">
<textarea id="notes" name="notes" ></textarea>
<span class="help-inline"></span>
<span class="help-block">Maximum length: 200</span>
</div>
</div>
</fieldset>
<fieldset>
<legend>Related Tags</legend>
<div id="profiles">
<div id="addMore" class="twipsies well profile">
</div>
<div class="manage">
<a class="addProfile btn success" id="addRT">Add related tag</a>
</div>
</div>
</fieldset>
<div class="actions">
<input type="submit" class="btn primary" value="Add Tag">
Cancel
</div>
</form>
<script type="text/javascript" charset="utf-8">
$('.addProfile').live('click', function(e) {
var template = $('.profile_template')
template.before('<div class="twipsies well profile">' + template.html() + '</div>')
renumber()
})
$('#form').submit(function() {
$('.phone_template').remove()
$('.profile_template').remove()
})
var renumber = function(phones) {
$('.profile').each(function(i) {
$('input', this).each(function() {
$(this).attr('name', $(this).attr('name').replace(/relatedTags\[.+?\]/g, 'relatedTags[' + i + ']'))
})
})
}
</script>
</div> </div> </div> </div>');
doc.close();
});
</script>
</body>
</html>
What happens is a syntax error because the #content is also an HTML. The quotation marks are messed up. Please help me. Thank you so much.
Well, you use jQuery is a tag... so I'll use a jQuery :)
What about:
$('#frame').contents().find('body').append('<div>your content</div>');
Or:
$('#frame').contents().find('body').html('<div>your content</div>');
Difference between the both examples?
.append(): http://api.jquery.com/append/
.html() : http://api.jquery.com/html/
run your javascript when the page is loaded.
$(function(){
var doc = document.getElementById('frame').contentWindow.document;
doc.open();
doc.write('<div class="container"> <div class="content"> <div class="row"> <div class="span14"> #content </div> </div> </div> </div>');
doc.close();
});

Prevent OnServerClick in OnClick?

I'm using ASP.NET and I have a link which has both onclick and onserverclick. Both are important, but I want the onclick to prevent the onserverclick running if at all possible.
Here is the item I'm playing with at the moment:
<ul class="clickables">
<asp:Repeater ID="MenuRepeater" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<li class=" <%# ((DataRowView)Container.DataItem)["CSSClass"]%>"
style="background-color: <%# ((DataRowView)Container.DataItem)["BackgroundColour"]%>">
<a id="A1"
runat="server"
onserverclick="LinkClick"
onclick=<%# "return javascript:LinkClick('" + ((DataRowView)Container.DataItem)["Postback"] + "')" %>
customid='<%# ((DataRowView)Container.DataItem)["UniqueID"]%>'
href='<%# ((DataRowView)Container.DataItem)["PageFile"]%>'>
</a>
<%# ((DataRowView)Container.DataItem)["DisplayName"]%>
</li>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
</ul>
Here's the JS I'm expecting to stop the postback:
function LinkClick(parameters) {
if (parameters[0] == "False") {
return false;
}
Am I missing something? Is this even possible? I know that I can prevent a normal postback by returning false in onclick, but can I stop the onserverclick?
UPDATE
After debugging a little more (been away from webdev for a while...), the JS function isn't firing...
UPDATE 2
Here is the full rendered page source:
<!DOCTYPE html>
<link rel="stylesheet" type="text/css"
href="iphone.css" />
<link href="MenuStyles.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="user-scalable=no, width=device-width" />
<script type="text/javascript" src="mootools-core-1.4.5-full-nocompat-yc.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form method="post" action="Main.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="YkYtJBVbLo0YmPPXHO5sO8FI5kAxszDeDe/bdeHgDCummp4bGaZKj3W6ihINzdq9PFQT6uCqE2eRXLhF1OEeKh8qJgRJnXWiisrDZ2ivw6JISfxuhIFP1VKKrZET9NIJqrJKpS2namuXzQL+yDJG8WGGvDrQ7oEBMDT6seSXr3zoowlA6tB4+gdbsPJ4utvNKCrhhTImpeXTzeaYCNV3t8QzsiGA7wK51Pgqo9vFQ6LH31NRYJEJ/yfhnnUcoSG6YR8SHNp+j7cGMVMoZPpgLu4bcMNSixHjGW+yin4YN7sf4wtXqQHIGFOwbSHM0VcAxd3is4lUJVYMoBH4pqAjjgBZMuaXPHwDfmZZk3Dk8feyn2btCh0nwXUrkAiAf8n1+a3hs9VfR0JeNs6x0WVzlMxgm4JFzIkthXtJ+632NaNh4rJyvib+j/Vs+HjtRFQXaIDj1fXp2KFniReSjZANiBaepyJqozJghhYnEB8MP1ZOePmrrbLCxUl1MD5Wn2bgFKkNSK25NC1hQoXdnZbEeA==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="zxCYbgjQBAQXVsCg6EwWqRNbeqa/5PzOIgwdhVB5mEasbEk06ik+VT9njAhsM8vF0ymfwdsNmbuX2R7iMJjdpqLMAVABvva4eorpK2PdajpD+g2RzFXI5SEEG9VjwQUXf3kKgb0KnPjWGYQdgZHGDQ==" />
</div>
<div>
<div class="button">Back</div>
<div class="button-bold">+</div>
<h1>AAR</h1>
<h2 id="lblQuestion">Please wait for a question...</h2>
<ul class="clickables">
<li class=" arrow"
style="background-color: White">
<a id="MenuRepeater_A1_0" onclick="return LinkClick('True')" customid="80f03602-cb67-4d46-99ea-4200459e6a48" href="javascript:__doPostBack('MenuRepeater$ctl01$A1','')">
</a>
Question 1
</li>
<li class=" "
style="background-color: LightGray">
<a id="MenuRepeater_A1_1" onclick="return LinkClick('False')" customid="91f76613-ecaa-47df-a5d6-5a921935b1f9" href="javascript:__doPostBack('MenuRepeater$ctl02$A1','')">
</a>
Question 2
</li>
</ul>
<ul class="clickables">
</ul>
</div>
</form>
<script>
$$('.clickables').each(function(clickable) {
var list = clickable.getElements('li');
list.addEvent('click', function() {
var link = this.getElement('a');
if(this.getFirst('a')) {
window.location = link;
}
});
});
function LinkClick(parameters) {
if (parameters[0] == "False") {
return false;
}
return true;
}
</script>
</body>
</html>
Edit 3
Even when I do:
onclick='return LinkClick(False)'
OR
onclick="return LinkClick(False)"
I still get:
onclick="return LinkClick('True')"
Edit 4
Here is the current rendered source:
<!DOCTYPE html>
<link rel="stylesheet" type="text/css"
href="iphone.css" />
<link href="MenuStyles.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="user-scalable=no, width=device-width" />
<script type="text/javascript" src="mootools-core-1.4.5-full-nocompat-yc.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<form method="post" action="Main.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="ATtNaDBRU6vswFif62qens2E35fTb32GNoGWb9g2UFbg0Pli0sVNrzGeLKgFI41ojer32c0dUpY2F54DIn0L0dQgi7XFwJCum71RivEO8THI+xsj3ACip5IKj0hPTlB0mDtjRUcRAPxTUDJlxNB2ZvpP1nAR8i7b/tsSrF5sP3Xx3JOb59POn4nxVDOTm80j0OAolK09Mo0leI9EzyQWbpig8Q8FaT7eKzCoJ1Z40TNWX24ZKsxsND4ebBfakOnI8qd2lNdBcJ9FrhBCTEJDCQksXs/rhyJXkksaonPGNFdtWMpiIyQDGkT0V6Q+CPt5fFnZZp4fbKZyRVMcs6XdxwHG3qTYJJgnDbfSvnswKce7la8JVSxoWy+dufG6gxIfJK2rKw0mhfQ21y90ZtkaKZ4CeZWB4TveHRhYJVlinC7bwXwKJGXhqcHJeJ0IoinTS+ZgsbuJOo3zHCslpWThP+ib7IVpmFx+nluy31L65Zy7dVoSZeySboBq10C9e1D3Tm0K5Pvcn/ovG7NmRupa+vgrcYEWQgb6QKym1aartoVmtPm1dWZiJzwA9X7j7Wn5mus2XrE5SXqbvp0bANO1rQ==" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="vi/Uef51SWAjwpFRuN3fwE5Y2FDB84KMHL6HjRIbWSKMEsSrg2RiGbteExTKFCbKhGe16A7xsn6DzMULMalMxqrg2yi9wkWZb0w2ifgCG6mmU0fH3V6zELQeACrtHDQ+4YlxeZ8k7HfGC592ammq3g==" />
</div>
<div>
<div class="button">Back</div>
<div class="button-bold">+</div>
<h1>AAR</h1>
<h2 id="lblQuestion">Please wait for the question...</h2>
<ul class="clickables">
<li class=" arrow"
style="background-color: White">
<a id="MenuRepeater_A1_0" onclick="return LinkClick(True);" customid="b88d214b-0d1c-4986-821e-c1650ffbdbfd" href="javascript:__doPostBack('MenuRepeater$ctl01$A1','')">
</a>
Question 1
</li>
<li class=" "
style="background-color: LightGray">
<a id="MenuRepeater_A1_1" onclick="return LinkClick(False);" customid="d566775f-4bee-4069-adb0-27e8cf8057d9" href="javascript:__doPostBack('MenuRepeater$ctl02$A1','')">
</a>
Question 2
</li>
</ul>
<ul class="clickables">
</ul>
</div>
</form>
<script>
$$('.clickables').each(function(clickable) {
var list = clickable.getElements('li');
list.addEvent('click', function() {
var link = this.getElement('a');
if(this.getFirst('a')) {
window.location = link;
}
});
});
function LinkClick(parameters) {
if (parameters[0] == "False") {
return false;
}
return true;
}
</script>
</body>
</html>
Update 5
So if I leave the method and just return true/false it should stop the postback? This doesn't work (more rendered source).
<!DOCTYPE html>
<link rel="stylesheet" type="text/css"
href="iphone.css" />
<link href="MenuStyles.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="user-scalable=no, width=device-width" />
<script type="text/javascript" src="mootools-core-1.4.5-full-nocompat-yc.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title></head>
<body>
<script>
function LinkClick(parameters) {
if (parameters[0] == "False") {
return false;
}
return true;
}
</script>
<form method="post" action="Main.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="PiZp7nhFhCoiWV3slT5szv5Z5GAkeDWYHj7QpAPmnwSoKxWg6Zm9HTQGkZXS2Osddx6KwS0eGu/ZMaLjgxVBm1U+Eszzf/OjmAbB78jPAeSwW8GwXRUUp984a7cPZc9cYajKHkhBVtuuALV6HSsT3oRzEPlziohjgWGiV8HFAEOd1CWTj+RAC3B/mWcmrFcexzpR1XhQgnV5LQC7GplUB9Y2E/rb8MFQHfYsRxG5GjWJ5zqe51FhwstLL/dbSklaBkRlFHyFyZNUeA74My6AHCOAWbUjZ42sVcMjaSVnM1zZsxQtSG8+UdbshaLZ9Gz5SOB0Vq4fS8J+TrUlswsSLqQ77Q+m2ouZG+jhPf7jKC59KvIYGlKHkgYVqCvhqhkIG91xg7k9M3f5KAf0yOB6yaesVxnWBCC+UQWcKRePIV9tq2eE8C+8F+rLCPJ6RXgUzpC+DvVmlQMHzmiXWLehtymb2HRX4O/2RUJxLDlVP/8=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="aQDXp34k4YJiEBt3URBFL0do/c8NXsEmuBtFz8JLRhtXerYXPFYRZmyXIpCef68aO7itJ4EUwQ9eXl2KkxDndTmS4149nNN8BX3AoFLDgB0b4w6cNsn3nzoZ3ENnU4vExyeHdXVJyyVwmZruhoQ7GA==" />
</div>
<div>
<div class="button">Back</div>
<div class="button-bold">+</div>
<h1>AAR</h1>
<h2 id="lblQuestion">Please wait for a question...</h2>
<ul class="clickables">
<li class=" arrow"
style="background-color: White">
<a id="MenuRepeater_A1_0" onclick="return true;" customid="b88d214b-0d1c-4986-821e-c1650ffbdbfd" href="javascript:__doPostBack('MenuRepeater$ctl01$A1','')"></a>
Question 1
</li>
<li class=" "
style="background-color: LightGray">
<a id="MenuRepeater_A1_1" onclick="return false;" customid="d566775f-4bee-4069-adb0-27e8cf8057d9" href="javascript:__doPostBack('MenuRepeater$ctl02$A1','')"></a>
Question 2
</li>
</ul>
<ul class="clickables">
</ul>
</div>
</form>
<script>
$$('.clickables').each(function (clickable) {
var list = clickable.getElements('li');
list.addEvent('click', function () {
var link = this.getElement('a');
if (this.getFirst('a')) {
window.location = link;
}
});
});
</script>
</body>
</html>
You should not do onclick=<%# .... %>, because that automatically encodes output.
It should be something like:
<a onclick="javascript:return LinkClick('<%# ((DataRowView)Container.DataItem)["Postback"] %>')" href="something"></a>
Your output return LinkClick('True') is not even javascript call. That's why you don't see any error.
There is usefull link about asp.net inline expressions:
http://support.microsoft.com/kb/976112
Thank you all so much for your help. The issue was .NET's XSS stuff (built in, automagically screwing with you via the config file..)
Once I removed this line it worked, I guess the way I'm getting my server variable into the JS makes my site think it's being attacked... It's going to be a private site anyway, so XSS is being turned off. If anyone can find a better solution (safer) then please post and I'll try it out...
<httpRuntime requestValidationMode="4.5" targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
^^ Remove that line from Web.config (at your own peril)...
Have you checked to see that parameters[0] == "False"? Could be a string comparison issue? Or it could be that your text is actually outside of the link tag:
<a id="A1"
runat="server"
onserverclick="LinkClick"
onclick=<%# "return javascript:LinkClick('" + ((DataRowView)Container.DataItem)["Postback"] + "')" %>
customid='<%# ((DataRowView)Container.DataItem)["UniqueID"]%>'
href='<%# ((DataRowView)Container.DataItem)["PageFile"]%>'>
</a>
<%# ((DataRowView)Container.DataItem)["DisplayName"]%>
should probably be:
<a id="A1"
runat="server"
onserverclick="LinkClick"
onclick=<%# "return javascript:LinkClick('" + ((DataRowView)Container.DataItem)["Postback"] + "')" %>
customid='<%# ((DataRowView)Container.DataItem)["UniqueID"]%>'
href='<%# ((DataRowView)Container.DataItem)["PageFile"]%>'>
<%# ((DataRowView)Container.DataItem)["DisplayName"]%>
</a>
If I understood your question, then suppressing the onserverclick because of something that happended in the onclick event is quite simple:
<span class="psw">Forgot password?</span>
This is an actual forgot password link on one of my pages. The code behind ForgotPassword() method specified in the onserverclick event is never triggered unless a valid email address is present.
The 'checkForRequiredEmailAddress' method checks for its existence, structure and correctness and then returns true or false depending on the outcome of the checks.
I know your question says that you tried this, but it is definitely working for me so I can only assume it is something silly. Maybe the missing semi-colon in the click event makes a difference.

Categories

Resources