Hi I am displaying a pp up window based on the value stored in a localStorage.In the pop up window there is a form containing email and password.The user has to enter his email and password.Now what I need is that, the email entered by user has to be sent to a url and the url returns a status(either 1 or 0).If the url returns 1 then the user can just continue with the log in process.Otherwise an error message should be shown.The url is in the format http://www.calpinemate.com/employees/attendanceStatus/email/3".Here in the place of email highlighten should come the email entered by user in the form.In this way I have to pass the email.In this way I am doing form validation.But I don't know how to do.
Here is my userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" />
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
This is the form in the pop up window
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
login();
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
function login(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
localStorage.username=userStr;
localStorage.password=pwd;
}
else{ alert('error');}
}
}
});
var url = urlPrefix + encodeURIComponent(userStr) + urlSuffix;
req.open("GET", url);
req.send(null);
}
});
This is my javascript.When the user presses the log in button,whatever the user enters in the email textbox gets stored in localStorage.username.Now what I need is that I have to check whether such an email id exists by passing the email to the above specified url.And if it exists only it should be stored in localStorage.username.Please anyone help me. I have tried using the above code.But noting happens.Please help me
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
It is a contact form. You can change it to validation.
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.
Related
I have a password-protected button that will redirect a user to a specific URL when the password is entered. It works fine but what I want to do is depending on what password the user enters, they will be taken to a URL which corresponds to what they entered. Let's say 'test' was entered in the box, this will redirect users to 'test.com/test/test.html' but if the user entered 'test1' then they'll be redirected to 'test.com/test1/test1.html'. Is there any way to do this? This is my code:
<body>
<div id="title">
<span>WELCOME TO</span> <span style="font-size:80px"><br>
AiZen</span>
</div>
<div class="button_container">
<button class="btn" id="HyperLink1" onclick="location.href='home.html';return ValidatePassword()"><span>Enter Now</span></button>
</div>
<script>
function ValidatePassword() {
var a = prompt("Enter the password. You know it right?", "");
if (a == "test") {
return true
} else {
alert("No match. Try again.")
}
return false
}
</script>
</body>
Assuming that you don't have access to a backend app server, or that you don't want to use it for this, you can do something like
document.getElementById("name").addEventListener("input", function(e) {
var val = e.target.value;
var form = e.target.closest("form");
//test.com/test1/test1.html
form.action = "http://test.com/" + val + "/" + val + ".html";
console.log("action: " + form.action);
});
<form>
<input name="name" id="name" />
<input type="submit">
</form>
I want to make the link in this change depending on whether the password is correct. I want to set one password and I only know html and minimal JS. I think I have it set so that when the password is wima it will change the href and allow the link to work. That doesn’t happen. Can I have some help?
function login()
var password = getElementById("password"); {
if (password = "wima") {
getElementById("submit").href = "/pages/home.html";
} else {
getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA"><br> Password
<input id="password" type=password placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>
There are a few issues with your JavaScript.
<script language="JavaScript">
function login()
var password = getElementById("password"); // this gets the element, not the value of the element
{ // this curly brace is in the wrong place
if (password = "wima") { // this sets the value of the password var to "wima"
getElementById("submit").href="/pages/home.html";
}
else {
getElementById("submit").href="index.html";
}
}
</script>
Here is your code, cleaned up.
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") { // use == to compare value
document.getElementById("submit").href="/pages/home.html";
}
else {
document.getElementById("submit").href="index.html";
}
}
</script>
Another issue here is that you shouldn't be changing the href on the element used to execute the login() function.
You could redirect the user to the new page like so:
<script language="JavaScript">
function login() {
var password = document.getElementById("password").value;
if (password == "wima") {
window.location.href="/pages/home.html";
}
else {
window.location.href="index.html";
}
}
</script>
I guess you are doing it wrong if you want to change the href value based upon input type text. You should make a blur/change event on password input text. Based upon password value when user clicks on href he should be redirected accordingly.
Check this out:
function login() {
var _password = document.getElementById("password").value;
if ("wima" == _password) {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type=text placeholder="WIMA">
<br> Password
<input id="password" type=password placeholder="WIMA" onblur="login()">
<br>
<a class="button" id="submit" href="#">
Submit
</a>
</p>
Here is a form validator with a switch.
function validateForm() {
var x = document.forms["myForm"]["password"].value;
switch (x) {
case "":
alert("Name must be filled out");
return false;
break;
case "wima":
return true;
break;
default:
alert("Error: Wrong Password.");
document.location.href = "https://stackoverflow.com/search?q=notloggedin";
// Replace the link above with your error link return
return false;
}
}
<!-- Replace action link with your successful link -->
<form name="myForm" action="https://stackoverflow.com/search?q=login" onsubmit="return validateForm()" method="post">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
Your password is visible in text if someone inspects the html/javascript. So this method of security is not advised. For basic concepts it is interesting to have a link change based on input. Try this.
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" >
Submit
</a>
</p>
<script>
var password = document.getElementById('password');
password.addEventListener('change', enableLogin);
var submit = document.getElementById('submit');
function enableLogin() {
if (password.value == "wima") { // it is an easy mistake (= or ==)
submit.href = "/pages/home.html";
} else {
submit.removeAttribute('href');
}
}
</script>
A few things happened here:
The value inside a <input> is accessed by .value;
You misplaced the {
getElementById is not a global method it has to be called on the element you want to select in (in your case the document itself)
To test if two values are equal use === in js
function login() {
var password = document.getElementById("password").value;
if (password === "wima") {
document.getElementById("submit").href = "/pages/home.html";
} else {
document.getElementById("submit").href = "index.html";
}
}
<p>
Username
<input id="username" type="text" placeholder="WIMA"><br> Password
<input id="password" type="password" placeholder="WIMA"><br>
<a class="button" id="submit" href="#" onclick="login()">
Submit
</a>
</p>
Is there any "right" way to get response from server without using JQuery/AJAX and of course without refreshing page?
server.js:
var http = require('http');
var url = require('url');
var qs = require('querystring');
var static = require('node-static');
var file = new static.Server('.');
http.createServer(function(req, res) {
if (req.method == 'POST' && req.url == "/reglog.html") {
var body = '';
req.on('data', function (data) {
body += data;
// Destroy connection if data is too large for it
if (body.length > 1e6) {
req.connection.destroy();
}
});
req.on('end', function () {
//it's time to parse body
var post = qs.parse(body);
//send response everything is ok
if (post.email.length > 0 && post.pswrd.length > 0 && post.login.length > 0) {
//also console.log to see what was sent from client
console.log(post);
res.end('Everything is good!');
} else {
// ...or not ok
res.end('Everything is bad!');
}
});
} else if (method = 'GET') {
file.serve(req, res);
}
}).listen(8080);
So, there's reglog.js:
var xhr = new XMLHttpRequest();
var uemail = document.getElementById("email"); //HTML element for user's email
var ulogin = document.getElementById("login"); //HTML element for user's login
var upswrd = document.getElementById("pswrd"); //HTML element for user's password
var message = document.getElementById("message"); //HTML element for response from server
function hide(tout) {
if (tout === undefined) tout = 2500;
return setTimeout(function() {
message.innerHTML = "";
}, tout);
}
document.getElementById("btn").onclick = (function createUser(){
var email = uemail.value;
var login = ulogin.value;
var pswrd = upswrd.value;
//XHR part starts//
var body = "email="+email+"&login="+login+"&pswrd="+pswrd;
//I know that email, login and pswrd should be with encodeURIComponent, but in my case it's not a problem and using it won't solve my main problem
xhr.open("POST","/reglog.html",true);
xhr.send(body);
message.style.color = "black";
xhr.onload = function() {
message.innerHTML = xhr.responseText;
}
//XHR part ends//
});
document.getElementById("lbtn").onclick = (function logMenu(){
document.getElementById('logform').style.display = "block";
document.getElementById('regform').style.display = "none";
});
document.getElementById("rbtn").onclick = (function regMenu(){
document.getElementById('regform').style.display = "block";
document.getElementById('logform').style.display = "none";
});
And reglog.html:
<HTML>
<HEAD>
<meta charset="utf-8">
<style>
.button{
position: absolute;
top: 45%;
bottom: 55%;
left: 15%;
}
</style>
</HEAD>
<BODY>
<form id="regform" action="/reglog.html" style="display:block;">
<center><p>Register</p>
E-mail: <input type="email" id="email" name="email" autocomplete="off"><br>
Login: <input type="text" id="login" name="login" required autocomplete="off"><br>
Password: <input type="password" id="pswrd" name="password" required autocomplete="off"><br>
<span id="message"></span><br>
<div class="button">
<input type="submit" id="btn" value="Register"/><br><br>
<input type="button" id="lbtn" value="Back to log in"/></div>
</center>
</form>
<form id="logform" style="display:none;">
<center><p>Log in</p>
Login: <input type="text" id="login2" autocomplete="off"/><br>
Password: <input type="password" id="pswrd2" autocomplete="off"/><br>
<span id="message2"></span><br>
<div class="button">
<input type="button" id="btn2" value="Log in"/><br><br>
<input type="button" id="rbtn" value="Registration"/></div>
</center>
</form>
<script async src="/reglog.js"></script>
</BODY>
</HTML>
As you can see I can get response on client side in
<span id="message"></span>
But I can see it for ~0.5 sec and after that there would be page refreshing. And that is not the best way to see results. My question: is it possible to see this response in "span" for more than ~0.5 sec? I mean, maybe refresh page and then show this response? I don't get how to do it because there is always response coming (for 0.5 sec) and then page refreshing.
Also I don't know if it's possible to do that without AJAX/JQuery.
I would glad to get any help because it's the question that torments me for two days, and I didn't find any reasonable answer via google.
Your code looks fine you just need to prevent the default action of the form submitting the traditional (page reload) way when you click the submit button.
document.getElementById("btn").onclick = (function createUser(e){
e.preventDefault();
// rest of function
});
I am trying to use a simple jquery/php newsletter script. The script works fine. As I enter name and email and hit the submit button, it saves data into a .txt file, and display a success message along with the form. Now, I would like to modify the script. I do not want the form to be seen as I hit the submit, instead it should show the success message only "Thank you." Being very novice to javascript, I have so far figured out that I need to "fadeOut" the form after clicking the submit button.
I think the code might be look like
$("#submit").on("click", function(e) {
e.stopImmediatePropagation();
$("#signup").fadeOut(280, function() {
// callback method to display new text
// setup other codes here to store the e-mail address
$(this).after('<p id="success">Thank you</p>');
});
});
I have tried to integrate this code, but due to my limited JS experience I cannot do it successfully.
Here is my original jquery script
var error_1 = "Please enter your valid email address";
var error_2 = "Please enter your name";
var thankyou = "Thank you";
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function $Npro(field) {
var element = document.getElementById(field);
return element;
return false;
}
function emailvalidation(field, errorMessage) {
var goodEmail = field.value.match(/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/);
apos = field.value.indexOf("#");
dotpos = field.value.lastIndexOf(".");
lastpos = field.value.length - 1;
tldLen = lastpos - dotpos;
dmLen = dotpos - apos - 1;
var badEmail = (tldLen < 2 || dmLen < 2 || apos < 1);
if (!goodEmail || badEmail) {
$Npro("Error").innerHTML = errorMessage;
$Npro("Error").style.display = "inline";
field.focus();
field.select();
return false;
} else {
return true;
}
}
function emptyvalidation(entered, errorMessage) {
$Npro("Error").innerHTML = "";
with(entered) {
if (trim(value) == null || trim(value) == "") { /*alert(errorMessage);*/
$Npro("Error").innerHTML = errorMessage;
$Npro("Error").style.display = "inline";
return false;
} else {
return true;
}
} //with
} //emptyvalidation
function signup(thisform) {
with(thisform) {
if (emailvalidation(email, error_1) == false) {
email.focus();
return false;
};
if (emptyvalidation(name, error_2) == false) {
name.focus();
return false;
};
}
$("#submit, #myResponse").hide(); // Hide the buttom and the message
$("#loading").show(); // show the loading image.
params = $("#subform").serialize();
$.post("optIn.php", params, function(response) {
//alert(response); //may need to activate this line for debugging.
$("#loading").hide();
$("#myResponse").html(thankyou); //Writes the "Thank you" message that comes from optIn.php and styles it.
$('#myResponse').css({
display: 'inline',
color: 'green'
})
$("#submit").show();
})
return false;
}
Here is the html markup
<form onSubmit="return signup(this);return false;" method="post" name="subform" id="subform" action="
<?php echo optIn.php ?>">
<div>
<span style="FONT-FAMILY: Arial; FONT-SIZE: 12pt; font-weight:bold;">Subscribe to our newsletter</span>
</div>
<div style="margin-top:20px">
<div>
<label style="display: inline-block;width:135px">Email:</label>
<input type="text" id="email" name="email" value="">
</div>
<div>
<label style="display: inline-block;width:135px">Name:</label>
<input type="text" name="name" id="name" value="">
</div>
<div>
<div style="display:inline-block;width:135px;"> </div>
<input type="submit" id="submit" name="submit" value="Sign up">
</div>
<div style="width:100%">
<span id="Error" style="color:red;display:none;"></span>
</div>
<div id="myResponse" style="DISPLAY:none;"></div>
<div id="loading" style="display:none;">
<img src="wait.gif" alt="">
</div>
</div>
</form>
Here is my php code:
<?php
//ini_set('display_errors', 0);
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
$email = trim(htmlspecialchars($_REQUEST["email"]));
$name = trim(htmlspecialchars($_REQUEST["name"]));
$pfileName = "mails.txt";
$MyFile = fopen($pfileName, "a");
$nline="\"".$email."\"" ."," ."\"".$name."\"" ."\r\n";
fwrite($MyFile, $nline);
fclose($MyFile);
die;
?>
Try providing a .delay() so that the fadeOut() function has finished before attempting to display the success message:
$("#submit").on("click", function(e) {
e.stopImmediatePropagation();
$("#signup").delay(500).fadeOut(280, function() {
$(this).after('<p id="success">Thank you</p>');
});
});
If I understand you correctly you want the user to submit the information via your html form. Then you want the form to go away after you hit the submit button.
From reading the JQuery method you have tried I found one mistake that is preventing your form from fading out. You were using the wrong id for your form in your JQuery code(it should be subform according to your html). Note that I removed your PHP code so that I could create an example in jsfiddle for you. My sample posts to google.com to prevent your from getting an error page displayed in the results sections.
jsfiddle: fade out form on submission
$("#submit").on("click", function(e) {
//changed from e.stopImmediatePropogation()
e.preventDefault();
//#subform is the actual id of your form, you were using signup
$("#subform").fadeOut(280, function() {
// callback method to display new text
// setup other codes here to store the e-mail address
$(this).after('<p id="success">Thank you</p>');
});
});
I am developing a wordpress plugin and am having a bit of trouble with my form submission. When activated the plugin essentially creates a little contact form with three fields so that a user would be able to enter in their name, email and phone number and then click submit which would then validate the code and store it in a database.
The strange thing is when clicking the Submit button the data seems to be sent using a get method as it is displayed in the url. I am handling the click of the button with an ajax post in a javascript file though. Here is the form code:
<div id="formwrapper" style="border:solid;border-color:red;">
<form name="contact" action="">
<label><strong>Contact Us</strong></label>
</br>
</br>
<input type="text" name="name" placeholder="Name & Surname">
<label class="error" for="name" id="nameErr">Please enter your name and surname</label>
</br>
</br>
<input type="email" name="email" placeholder="Email Address">
<label class="error" for="email" id="emailErr">Please enter a valid email address</label>
</br>
</br>
<input type="phone" name="phone" placeholder="Cell or Landline">
<label class="error" for="phone" id="phoneErr">Please enter your cell or landline number</label>
</br>
</br>
<input type="submit" class="button" name="submit" value="Submit" id="submit_button">
</form>
</div>
And this is the javascript I am using to handle the click of the button:
$(".button").click(function() {
$(".error").hide();
var name = $("input#name").val();
if (name == "") {
$("label#nameErr").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#emailErr").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phoneErr").show();
$("input#email").focus();
return false;
}
var datastring = 'name=' + name + '&email' + email + '&phone' + phone;
$.ajax({
type:"POST";,
url: "bin/process.php",
data: datastring,
success: function() {
$('#formwrapper').html("div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
alert "hello";
return false;
}
Not only does clicking the button not properly post the values, it seems to activate some sort of search function within wordpress as all the posts disappear and return with a "Sorry , no posts matched your criteria" message.
You have an error in your js code
alert "hello";
is not valid use:
alert("hello");
Due to this your return false does not get triggered and the form submits as normal.
Use event.preventDefault instead of returning false so that you will detect errors like this better
$(".button").click(function(e){
e.preventDefault();
...
});
And as Joe Frambach points out another syntax error is in your ajax options
type:"POST";,
should be
type:"POST",
try this
$(".button").click(function() {
$(".error").hide();
var name = $("input#name").val();
if (name == "") {
$("label#nameErr").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#emailErr").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phoneErr").show();
$("input#email").focus();
return false;
}
var datastring = 'name=' + name + '&email' + email + '&phone' + phone;
$.ajax({
type:"GET";,
url: "bin/process.php",
data: datastring,
success: function() {
$('#formwrapper').html("div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
alert "hello";
return false;
}