assume that login.check() checks for validation of the fields after that I post the data to 'check.php' since it is an ajax request so to wait for the response I have taken a variable called flag(initialized with 'false'). When the response is processed I set the flag as 'true'. But, there is something is wrong with this script because the page freezes. But I cannot debug the script so please help me.
$('.login-form').submit(function(){
var flag = false , tag;
if(login.check() === false){
return false;
}
else{
$.post('check.php',{
"username":$('#username1').val(),
"password":$('#password1').val()
},function(data){
var obj = JSON.parse(data);
if(obj.status === false){
var server_alert = document.getElementsByClassName('server-alert')[0];
server_alert.innerHTML = obj.error;
server_alert.className = server_alert.className.replace('display-hide','');
tag = false;
flag = true;
}
else if(obj.status === true){
tag = true;
flag = false;
}
});
}
while(flag != true);
return tag;
})
Related
I am creating a form that asks for email and password and validates it. If it has any error, it pops on the same line. Below is my javascript code for it. When I fill the form and hit submit, the values get reset. Moreover, I do not see anything in the console. I tried using a random code console.log('Hanee') to test my code but nothing gets generated in the console tab. Could anyone tell me what's the issue here?
Also, here's the link to my login form: http://www2.cs.uregina.ca/~hsb833/215a/login.html
document.getElementById("login-form").addEventListener("submit",validateLogin,false);
function validateLogin(event){
var elements = event.currentTarget;
var emailValue = elements[0].value;
var passValue = elements[1].value;
checkEmail(emailValue);
checkPass(passValue);
}
function checkEmail(emailValue){
var regex_email = /^[/w]+#[a-zA-Z]+?\.[a-zA-Z]{2,3}$/;
var index = emailValue.search(regex_email);
var errorEmail = document.getElementById("errorEmail");
var valid = true;
console.log('Hanee');
if(index != 0){
errorEmail.style.display = 'inline';
}
}
function checkPass(passValue){
var password = document.getElementById("password");
var regex_pass = /[\w]+\S/;
var index = passValue.search(regex_pass);
if(passValue.length < 6){
console.log('password is invalid. Minimum length is 6');
errorPassLen.style.display = 'inline';
}
if(index != 0){
console.log('password is invalid. Please make sure there is no spaces in between');
errorPassFormat.style.display = 'inline';
}
}
form is refreshed after being submitted by default. To prevent that, use event.preventDefault(); in your validateLogin
Here is an example of a form with a username and password, maybe it will suit you and you can customize it for your needs
async function tebeFxhr() {
let logfil = 1;
let sotebe= false;
let tes =(logt) => {
return /^[a-zA-Z0-9]+$/ui.test(logt);
}
tes(gtebe)==true ? logfil++ : alert('Login cannot contain characters or spaces')
let textrf =(rutext) => {
return /[а-я]/i.test(rutext);
}
textrf(stebe)==true ? alert('The password cannot contain Cyrillic characters') : logfil++;
stebe.length < 8 ? alert('Password is very short') : logfil++;
stebe===ftebe ? logfil++ : alert('Enter the password 2 times so that they match')
if (logfil === 5){
const data = {data_0:gtebe, data_1:stebe, data_2:ftebe};
const response = await fetch("/form", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => {
return response.text();
})
.then((sotebe) => {
console.log(sotebe)
if(sotebe==='error-1'){
console.log('error-1')
}
else{
sotebe =='' ? location.replace("../") : alert(sotebe)
}
});
}
}
When submit event is triggered, all values are sent to server and get reset. If you want to prevent this, use event.preventDefault(); inside the event handling function validateLogin(event). Then, the values are not going to be reset!
Still If you want your values to be empty after submission, try below.
elements.forEach(e => e.value = '');
I am quite new to Javascript, so I ask for help because somehow I get stuck.
I dont want the input field to become empty after a page refresh - with some copy&paste of code parts I could partially solve it by using sessionStorage + setItem / getItem.
Now I would like the corresponding message also not become empty - at the moment it disappears when I refresh the page. What's the easiest way to get the message? Thank you for your help!
javascript:
let userInput;
let messageUserText;
var validUser = false;
onload = function (event) {
userInput = document.getElementById('usernameInput');
messageUserText = document.getElementById('userMsg');
}
function InputUser() {
const userName = usernameInput.value;
let messageUserName = '';
if (userName === '') {
messageUserName = 'EMPTY';
validUser = false;
} else {
messageUserName = 'OK';
validUser = true;
}
//THIS IS THE MESSAGE I WANT TO KEEP
messageUserText.innerHTML = messageUserName;
}
//KEEP INPUT AFTER SITE REFRESH
document.getElementById("usernameInput").value = getSavedValue("usernameInput");
//SAVE VALUE
function saveValue(e){
var id = e.id;
var val = e.value;
sessionStorage.setItem(id, val);
}
//RETURN SAVED VALUE
function getSavedValue (v){
if (!sessionStorage.getItem(v)) {
return "";
}
return sessionStorage.getItem(v);
}
html:
<body>
<form>
<input type="text" id="usernameInput" oninput="InputUser()" onkeyup="saveValue(this)">
</form>
<!-- THIS IS THE MESSAGE I WANT TO KEEP AFTER REFRESH -->
<div class=""><p id="userMsg"></p></div>
<script src="javascript.js"></script>
</body>
I tried a lot and have partially solved it. Now its able to save the input and associated message to keep them after site refresh.
But I need help to keep the message color and the state of the submit button . I made some tries but cannot get it going. Please can someone tell me how to write the code? I commented it below.
Javascript:
.
.
.
onload = function (event) {
userInput = document.getElementById('usernameInput');
messageUserText = document.getElementById('userMsg');
setPasswordButton = document.getElementById('passwordButton');
}
function InputUser() {
const userName = usernameInput.value;
let messageUserName = '';
if (userName === '') {
messageUserText.style.color = 'red';
messageUserName = 'Message 1';
validUser = false;
} else {
messageUserText.style.color = 'green';
messageUserName = 'Message 2';
validUser = true;
}
messageUserText.innerHTML = messageUserName;
//Save Message to sessionStorage
var idUserMsg = userMsg.id;
var valUserMsg = messageUserText.innerHTML;
sessionStorage.setItem(idUserMsg, valUserMsg);
//Save Message Color (messageUserText.style.color)
//How?
//Button Activation
if (validUser) {
setPasswordButton.disabled = false;
} else {
setPasswordButton.disabled = true;
}
//Save Button state (setPasswordButton.disabled)
//How?
}
//Keep Inputs after site refresh
document.getElementById("usernameInput").value = getSavedValue("usernameInput");
document.getElementById("userMsg").innerHTML = getSavedValue("userMsg");
//Keep Message Color How?
//Keep Button state How?
//Save sessionStorage
function saveValue(e){
var id = e.id;
var val = e.value;
sessionStorage.setItem(id, val);
}
//Return from sessionStorage
function getSavedValue (v){
if (!sessionStorage.getItem(v)) {
return "";
}
return sessionStorage.getItem(v);
}
I am trying to show alert message when user failed to login with url value .
<script type="text/javascript">
<!--
var retVal = confirm("Login FAILED! Do you want to continue ?");
if( retVal == true ){
window.location.href = "login.php";
return true;
}else{
alert("User does not want to continue!");
return false;
}
//-->
</script>
this is url value
/?redirect_to=%2Fstarstruckmedia%2F%3Flogin%3Dfailed%26redirect_to%3D%252Fstarstruckmedia%252F&login=failed
You can't use return unless you are in a function. Take those lines out and your code works.
var retVal = confirm("Login FAILED! Do you want to continue ?");
if(retVal){
window.location.href = "login.php";
} else {
alert("User does not want to continue!\n" + window.location.href);
}
You can obtain the url of the current page using window.location.href. See this for details.
var retVal = confirm("Login FAILED! Do you want to continue ?");
if( retVal == true ){
window.location.href = "login.php";
}else{
alert(window.location.href);
}
I am working on a registration form with jquery ajax. My jQuery Code is as follow :
function validateData()
{
var email = jQuery("#email").val();
var username = jQuery("#username").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var regex = new RegExp(/^\+?[0-9(),.-]+$/);
if(!emailReg.test(email))
{
alert('Please enter valid email');
return false;
}
var agreement = jQuery("#agereement").is(":checked");
if(agreement == false)
{
alert("Please agree with the agreement !!! ");
return false;
}
var pass = jQuery("#password").val();
var repass = jQuery("#repeatpass").val();
if(pass != repass)
{
alert("Password & Repeat Password Should be same");
return false;
}
var FirstData = "email=" + email+"&username="+username;
var url = "ajaxcheck.php";
jQuery.ajax({
dataType : 'html',
type: 'GET',
url : url,
data : FirstData,
complete : function() { },
success: function(data)
{
if(data == '')
{
alert("No Problem");
var flag = "true";
}
else{
alert("Username Or Email ID Already Exists");
var flag = "false";
}
}
});
alert(flag);
return flag;
}
</script>
When I submit the form and enters the value of username which is already exists in DB then it alerts the Username Or Email ID Already Exists but submit the form instead of staying on the page. What Should I do if it error comes then it should stay on the page instead of submitting the form
When you write:
var flag = "true";
…
var flag = "false";
…
return flag;
The problem is that "true" and "false" are strings containing the word “true” or “false”. To get the actual boolean values true or false, get rid of the quotes:
var flag = true;
…
var flag = false;
…
return flag;
Event handlers only understand boolean return values, not strings.
Use onsubmit in form tag
<form onsubmit="return validateData();">
....
<input type="submit">
</form>
I'm trying to help you from another angle.
Here is an example on how to do form validation (with bootstrap/php/jquery): http://formvalidation.io/examples/contact-form/
Ajax ".done" happens when you get a successful response from the server and ".fail" happens when sending a request or receiving the response has failed. Assuming you want to check if email exists then you can use something in the lines of:
if(response.IsEmailValid === 'false')
{
$('#alertContainer')
.removeClass('alert-success')
.addClass('alert-warning')
.html('Sorry, email has been taken')
.show()
}
You're setting flag to strings, not boolean values. Try using true and false instead of "true" and "false", both of which are truthy.
I am trying to make a live ajax searchbar on keyup event.
When I type one character the page changes url and resets my input text. How can I prevent the page from refreshing as I write more characters?
<script type="text/javascript">
function getSearch(str){
var u = document.getElementById("search").value;
if(str.length == 0){
status.innerHTML = 'field is empty';
}
if(u != "") {
se.onreadystatechange = function(){
if (se.readyState == 4 && se.status == 200){
status.innerHTML = se.responseText;
}
}
}
}
</script>
Your ajax request lacks some configuration. You need to tell the request itself which url it should call, and specify the method. Just change those lines:
status.innerHTML = 'Verifying...';
//window.location.replace("search.php?search="+str);
// this is why your page reloads. you want to remove this
var se = new XMLHttpRequest();
se.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
se.onreadystatechange = function(){
if (se.readyState == 4 && se.status == 200){
status.innerHTML = se.responseText;
}
}
se.open('POST',"search.php?search="+str);
// you need to open the request, specifying the method and the url
se.send();
here is an interesting read on ajax requests