onreadystatechange not submit forms or it always submits forms - javascript

I want my input email address to be checked on registration page. I am right now using onreadystatechange to get the response from database with responseText. If responseText is true, then do not submit the form, otherwise, submit.
However, my code will always submit my forms even if the condition is true.
//////////////HTML file//////////////////
<form action="regist.php" method="post" id="submitForm">
<label>*Email:</label>
<label class="validate" id="emailError">XXXX#XXXX.XXX</label></br>
<input type="text" id="email" name="email"/></br>
<label>*First Name:</label>
<label class="validate" id="firstnameError">Letters only!</label>
<input type="text" id="firstname" name="firstname"/></br>
<label>Last Name:</label>
<input type="text" id="lastname" name="lastname"/></br>
<label>*Password:</label>
<label class="validate" id="passwordError">at least 6 characters!</label>
<input type="password" id="password" name="password"/></br>
<label class="validate" id="used">Email has been used!</label></br>
<button id="Validate">Register</button>
</form>
////////////////////JS file////////////////
$(document).ready(function () {
$("#regi").click(function () {
var popup = $("#register").dialog({modal: true});
popup.show();
});
$("#Validate").click(function () {
validate();
});
});
function validate() {
var email = document.getElementById("email").value;
var error = $("#used");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend.php?req=checkDuplicate&user=" + email, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText == 1) {//check if email existed in db, return 1
error.show();
console.log("find match! Do not proceed!!");
$('#submitForm').submit(false);
}
else {
error.hide();
console.log("Redirect");
$('#submitForm').submit(true);//only here should do redirect
}
}
}
xmlhttp.send();
}

First of all, you should read some documentation about jQuery submit.
function validate() {
var email = document.getElementById("email").value;
var error = $("#used");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend.php?req=checkDuplicate&user=" + email, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText == 1) {//check if email existed in db, return 1
error.show();
console.log("find match! Do not proceed!!");
// if you don't want to proceed just don't call submit !
// $('#submitForm').submit(false);
}
else {
error.hide();
console.log("Redirect");
//$('#submitForm').submit(true);//only here should do redirect
// remove the true value using jQuery to trigger the submit
$('#submitForm').submit();
}
}
}
xmlhttp.send();
}
Using jQuery.get you can have same result with that :
function validate() {
var email = $("#email").val();
var error = $("#used");
var url = "backend.php?req=checkDuplicate&user=" + email;
$.get(url , function( data ){
if(data===1){
error.show();
console.log("find match! Do not proceed!!");
}else{
error.hide();
console.log("Redirect");
$('#submitForm').submit()
}
});
}
I hope this will help you.

Related

Classic Asp Newsletter suscription problem with Ajax trying to have a loader and confirmation message without refresh the page , Im stuck

STRANGE BEHAVIORS
No matter how I organize the code:
Submit button makes the loader and then the confirmation message appears even if you dont fill the email input form
Sometimes refresh the page , sometimes dont
What I want is simple:
a) If the email input form is unfilled then dont do nothing just expect the html5 input validation message.
b) If all is ok and the email input is correctly filled then have the loader appears and then the confirmation message.
I have 3 days in a row, experimenting. I'm STUCK.
Thanks in advance
AJAX / JS
function ajaxFunction() {
var form = document.getElementById("contactForm");
function handleForm(event) { event.preventDefault(); }
form.addEventListener('email_suscribe', handleForm);
var ajaxRequest;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("loading").innerHTML = ''; // Hide the image after the response from the server
document.getElementById("ajaxDiv").innerHTML = xmlhttp.responseText;
}
}
document.getElementById("loading").innerHTML = '<img src="images/loading.gif" />'; // Set here the image before sending request
xmlhttp.open("GET", "includes/suscripcion.asp?email_suscribe=<%=request.form("email_suscribe")%>", true);
xmlhttp.send();
}
FORM
<form id="contactForm" name="contactForm">
HTML
Email Input Form
<input name="email_suscribe" type="email" autocomplete="on" required="required" class="footer_suscribir" placeholder="Correo Electronico" maxlength="60">
Submit Button
<button name="submit" onclick="ajaxFunction();" class="footer_suscribete"><strong>Suscribete</strong></button>
Loader
<span id="loading"></span>
Real Time Confirmation Message
<div id="ajaxDiv"></div>
You can check this.
HTML
<input name="email_suscribe" type="email" autocomplete="on" required="required" class="footer_suscribir" placeholder="Correo Electronico" maxlength="60">
<input type="button" onclick="subscribe()">
<span id="loading"></span>
<span id="ajaxDiv"></span>
JS
<script>
function subscribe() {
var email=$(".footer_suscribir").val()
if (isEmail(email)===true) {
$("#loading").fadeIn("fast")
$.ajax({
type: 'POST',
crossDomain: true,
url: "postdata.asp",
data: {
"email": email
},
success: function (resp) { //resp: return from postdata.asp
$("#ajaxDiv").html(resp)
$("#loading").fadeOut("fast")
},
error: function (e) {
$("#ajaxDiv").html("AN ERROR OCCURRED")
$("#loading").fadeOut("fast")
}
});
}
else {
$("#ajaxDiv").html("EMAIL FORMAT ERROR")
}
}
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
</script>
POSTDATA.ASP
<%
'...
'DB CONNECTION
'...
' SAMPLE DB EXECUTION
email=request.form("email")
Set rsa=Server.CreateObject("Adodb.Recordset")
Sorgu="Select TOP 1 email from subscribers WHERE email='"&email&"'"
rsa.Open Sorgu, bag, 1, 3
if rsa.bof then
rsa.addnew
rsa("email")=email
rsa.update
response.write "SUCCESS"
else
response.write "ALREADY EXISTS"
end if
rsa.close
set rsa=nothing
%>

Best way to do firebase phone authentication on client side and create account in database in server

My Form:
<form class="signup" >
<p style="display:inline-block;">Signup or </p>
<p class="showcursor"style="display:inline-block;color:orange;" onclick="showlogin()">login to your account</p>
</br>
<input name="phone" type="text" placeholder="Enter Phone number">
<input name="name" type="text" placeholder="Enter name">
<input name="email" type="text" placeholder="Enter email">
<input name="password1" type="text" placeholder="Enter password">
<input name="password2" type="text" placeholder="Retype password">
<button class="signin" id="otp" type="button" onclick="signup()" style="display:inline-block;"><b>Continue</b></button>
</form>
My scripts:
function signup() {
var formdata = new FormData(document.getElementsByClassName("signup")[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'cartserver.php', true); //Here I check if the phone number already exists
// Set up handler for when request finishes
xhr.onload = function() {
if (xhr.status === 200) {
//File(s) uploaded
var arr = JSON.parse(this.responseText);
if (arr[0] == 1) {
onSignInSubmit(arr[2]); //here passing the phone number
} else {
alert(arr[1]);
}
} else {
alert("Check your connection!");
}
};
formdata.append("id", 1);
xhr.send(formdata);
}
function onSignInSubmit(phone) {
var phoneNumber = phone;
var appVerifier = window.recaptchaVerifier;
firebase
.auth()
.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function(confirmationResult) {
window.confirmationResult = confirmationResult;
})
.catch(function(error) {
console.log(error);
});
}
function submitPhoneNumberAuthCode() { //when user submits the code
var code = document.getElementById("code").value;
confirmationResult
.confirm(code)
.then(function(result) {
var formdata = new FormData(document.getElementsByClassName("signup")[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'createaccount.php', true); //create his account
xhr.onload = function() {
if (xhr.status === 200) {
//File(s) uploaded
alert(this.responseText);
}
};
xhr.send(formdata);
}
.catch(function(error) {
console.log(error);
});
}
My problem is that suppose user enters the correct code but he change the phone number while doing it, then the account gets created with other phone number , also if user changes the javascript and place account creation code inside catch error function then the account gets created again.

Reading the first childnodes only

Hi im a newbie ive been trying to create a login form wherein the username and password are stored in xml file.However whenever i type my username and password it only allows a username A and password 12345 to login successfully.but if i type B password 12345.Its not working anymore.Below is my code.
users.xml
<users>
<user>
<username>A</username>
<password>12345</password>
</user>
<user>
<username>B</username>
<password>12345</password>
</user>
</users>
try.html
<!DOCTYPE HTML>
<html lang="en-US">
<head>
</head>
<body>
<form id="frmlogin" name="frmlogin" method="post" action="Login" onsumbit="return false;">
<p>ENTER USER NAME <input type="text" name="login_username" id="username"></p>
<p> ENTER PASSWORD <input type="password" name="login_pass" id="password"><br><br>
<input type="button" class="button" value="Log in" onclick="login()">
</p>
</form>
<script>
window.login = function(e)
{
if (document.frmlogin.login_username.value == "")
{
alert("User name is not blank");
return;
}
else if(document.frmlogin.login_pass.value == "")
{
alert("Password is not blank");
return;
}
else
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "users.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xhttp.responseXML;
var ktra = true;
var xml = xmlDoc.childNodes[0].childNodes[1];
var name = xml.childNodes["username"];
var pass = xml.childNodes["password"];
for(var i =1 ;i<xml.childNodes.length;i++){
if(xml.childNodes[i].nodeName =="username")
name = xml.childNodes[i];
if(xml.childNodes[i].nodeName =="password")
pass = xml.childNodes[i];
}
if(name.textContent == frmlogin.login_username.value && pass.textContent== frmlogin.login_pass.value)
{
ktra = true;
}
else
{
ktra=false;
}
if(ktra == true)
{
alert("Login Successfully !!!");
}
else
{
alert("Login Failed !!!");
}
}
}
</script>
</body>
</html>

JQuery form submission not working with API

I am trying to retrieve date from a form submission to use in a SmartyStreet API request. It's not outputting the response from the API.
HTML:
<div class="form-style-5">
<form id="myForm">
<fieldset>
<legend><span class="number">1</span> Input Address</legend>
<input type="text" id="street" name="street" placeholder="Street">
<input type="text" id="city" name="city" placeholder="City">
<input type="text" id="state" name="state" placeholder="State">
<input type="submit" value="Submit" />
</fieldset>
</form>
<fieldset>
<legend><span class="number">2</span> Results</legend>
<div id='resultBox'>
</div>
</fieldset>
</div>
JS:
AUTH_ID = "123456789";
AUTH_TOKEN = "123456789"
$("myForm").submit(function(event) {
street = $("#street").val()
city = $("#city").val()
state = $("#state").val()
var xhr = new XMLHttpRequest();
xhr.open("get", "https://us-street.api.smartystreets.com/street-address?street=" + street + "&auth-id=" + AUTH_ID + "&auth-token=" + AUTH_TOKEN, true);
xhr.send();
var addresses = JSON.parse(xhr.responseText);
console.log('Hello')
$( "#resultBox" ).text(addresses).show();
event.preventDefault();
});
Any help is appreciated, I just want to know why it isn't working and if there is a better way. Thanks
You can use the onreadystatechange property to monitor the state of your request,when the state changes the function gets called, when the status of the request is 4 (Completed) and Response status code is 200 (OK), then you change the address text using the returned json data from the response text property. I hope this helps.
$("myForm").submit(function(event) {
event.preventDefault();
street = $("#street").val()
city = $("#city").val()
state = $("#state").val()
var xhr = new XMLHttpRequest();
xhr.open("get", "https://us-street.api.smartystreets.com/street-address?street=" + street + "&auth-id=" + AUTH_ID + "&auth-token=" + AUTH_TOKEN, true);
xhr.send();
var addresses;
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
addresses = JSON.parse(xhr.responseText);
$( "#resultBox" ).text(addresses).show();
console.log('Hello');
}
}
});
Try below code. Use document.ready function
<script>
AUTH_ID = "123456789";
AUTH_TOKEN = "123456789"
$(document).ready(function(){
$("#myForm").submit(function(event) {
street = $("#street").val()
city = $("#city").val()
state = $("#state").val()
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var addresses = JSON.parse(xhr.responseText);
console.log(xhr.responseText)
$( "#resultBox" ).text(addresses).show();
}
};
xhr.open("get", "https://us-street.api.smartystreets.com/street-address?street=" + street + "&auth-id=" + AUTH_ID + "&auth-token=" + AUTH_TOKEN, true);
xhr.send();
event.preventDefault();
});
});
</script>

Custom Live Validation Function

I've been trying to create my own custom LiveValidation (LiveValidation.com) function that connects to a database and checks if a username already exists. This is the relevant part of the form:
Username: <input type="text" name="username" id="username" class="textinput">
<script type="text/javascript">
var username = new LiveValidation('username');
username.add( Validate.Presence );
username.add( Validate.Length, { minimum: 3, maximum: 12 } );
username.add( Validate.Username );
</script>
This is my Validate.Username function:
Validate.Username = function(value, paramsObj){
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Sorry that username is taken!";
var http = new XMLHttpRequest();
var url = "usernamecheck.php";
var params = "username="+value;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
if(http.responseText == 'yes') {
return true;
} else {
Validate.fail(message);
return false;
}
}
}
http.send(params);
}
Here's the relevant part of usernamecheck.php:
if(mysql_num_rows($query) != 0 && $query) {
echo "no";
} else if ($query) {
echo "yes";
} else {
echo "err";
}
The function seems to work fine (if I put alert('fail') above Validate.fail(message); I get an alert when a used username is used), but LiveValidation never shows the error message. Anyone know what I've done wrong?
Thanks
Hmmm... just looking at it real quick, could it be that "message" is not defined in your function ? It is defined in the parent function.

Categories

Resources