I am using a $.get function to check the connection to the server before submitting the ASP login form. If the get function is successful and returns a true then the form should submit, otherwise if it fails and returns false, it should not.
I have tried many different configurations, but everything I've tried has either rendered the button inoperable, or only showing a true, and never a false!
Any advice is appreciated. Thanks.
<asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Enter" ValidationGroup="LoginUserValidationGroup" class="submitButton" />
UPDATE - The code below executes the get function correctly, but I have a feeling the problem lies within $('form').submit();
When true is returned the page refreshes like it sent the data, but the system does not log the user in. Why is this!?
submitButton.click(function () { // capitalize username on login
var url = 'https://examplesite.com/';
$.get(url).done(function () {
if (usernameBox.val() === '') {
usernameBox.attr('placeholder', 'Username Required');
passwordBox.attr('placeholder', '');
usernameBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val() === '') {
passwordBox.attr('placeholder', 'Password Required');
usernameBox.attr('placeholder', '');
passwordBox.focus();
return false;
}
else if (passwordBox.length && passwordBox.val().length < 6) {
passwordBox.focus();
return false;
}
else {
alert('Successful - Now logging in');
$('form').submit();
}
}).fail(function () {
alert('Failed - No Connection');
});
return false;
});
};
$.get is an async function, so online is never set to what you think it is since the rest of the code is being processed before the call is complete. Move your logic into the .done part of it!
$.get(url).done(function () {
online = true;
if (online == true) {
alert('Success');
$('form').submit();
}
else if (online == false) {
alert('Cannot Connect');
return false;
}
else {
return false;
}
}).fail(function () {
online = false;
});
Related
This is most likely a repeat question since it's a common problem for learners, but I just cant find a to-the-point working solution for the issue (I've been trying to get on top this for ages!):
This works because there's no Ajax:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
function first(){
var bbb;
var test = prompt("enter a number");
if(test == 6){
bbb = true;
return bbb;
} else {
bbb = false;
}
}
function second(){
if(first()){
alert("returned true!!");
} else {
alert("returned false");
}
}
But I can't get this next piece of code to work, because the callback runs before the Ajax call is complete. I know deferred and promise are the modern way to sort callbacks like this, but after reading and watching TONS on the matter, I'm still missing some key logic or syntax and it just won't work for me.
Can someone help me get a working example of deferred in action with the following code? Then from there I'll be able to improve my learning about deferred, but currently I'm getting nowhere.
//-----------------------gets much more confusing with Ajax calls------------------
function firstAjax(){
var check = prompt("number between 1 and 10 to send (6 should return true from PHP...)");
$.post('remote.php',
{
check: check
},function(data) {
var returned = JSON.parse(data);
if(returned == true) {
alert(returned);
return true;
} else {
alert(returned);
return false;
}
});
}
function secondAjax(){
if(firstAjax()){
alert("successfull return");
} else {
alert("return failed"); //callback runs before the post returns...
}
}
Buttons to activate the functions:
<button type="button" onClick="second()">Run Local Javascript only </button>
<button type="button" onClick="secondAjax()">Run Ajax call with param passing</button>
And this is 'remote.php': simple if input = 6 return true.
<?php
$check = $_POST['check'];
if($check == 6){
echo json_encode(true);
} else {
echo json_encode(false);
}
?>
You are doing a asynchronous requests and firstAjax() will return undefined before the response have been received.
You need to define a callback function as a parameter in firstAjax(), and then call this function when the response have been received.
function firstAjax(callback) {
var check = prompt("number between 1 and 10 to send (6 should return true from PHP...)");
$.post('remote',
{check: check},
function (data) {
var returned = JSON.parse(data);
if (returned == true) {
alert(returned);
callback(true);
} else{
alert(returned);
callback(false);
}
});
}
function secondAjax() {
firstAjax(function(result){
if(result){
alert("successfull return");
}else{
alert("return failed");
}
});
}
Please help me, How to use two ajax field validation on button (if data already exist don't click on button or redirect same page) redirection stop?
This is my ajax code:
function validate()
{
return (chkunm() && chkemail());
}
function chkunm()
{
// alert ("hello");
var unm, http;
unm = document.getElementById("pupilname").value;
http= new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){
document.getElementById("s1").innerHTML=http.responseText;
}
if(http.responseText==true)
{
// alert ("Welcome");
return true;
}
else
{
// alert ("username already exists");
return false;
}
}
http.open("GET","getunm.php?unm="+unm,true);
http.send();
}
function chkemail()
{
// alert("hello");
// die();
var email, http;
email = document.getElementById("pupilpass").value;
http= new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4 && http.status==200){
document.getElementById("s2").innerHTML=http.responseText;
if(http.responseText==true)
{
// alert ("welcome");
return true;
}
else
{
//alert ("email already exists");
return false;
}
}
}
http.open("GET","getemail.php?email="+email,true);
http.send();
}
I want, if data is already exist...!! SO don't click on button .. How can possible.. Help me
Thanks
This answer might help you:
Basically you will have multiple ajax calls that bring back their check results. You will use when to wait for both before checking if you want to redirect or not.
Code:
$(document).ready(function(){
var check1, check2;
$("yourElement(s)").click(function(){
$.when(ajax1(), ajax2()) {
if(check1 || check2) {
// window.location - whatever your soul desires
}
}
}
function ajax1() {
return $.ajax({
url: "someUrl",
dataType: "json",
data: yourJsonData,
// whatever else you need,
success: function(result){
check1 = result;
}
});
}
// idem ajax 2 to get check2 value.
}
As you might have guessed, this code is not quite tested.
I hope this helps.
$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.
On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.
I have two questions from the coding below.
First, now i would like to perform validation before submission. How can I stop submission if some errors are detected from the validation function? Is it simply return false after each of the error msg? however, it seems still check all fields instead of stopping after getting one error.
Second, i would like to insert the data via php. Everytime, it can successfully add the data to the database, however, it always alert "Error: error". I dunno where does the error come from...
$(document).ready(function()
{
$('#test').click(function(){
validation();
});
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
}
else
{
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
}
else
{
}
//return false;
} // end of #validation
$('form').submit(function(){
validation();
$.ajax({
type: 'POST',
data:
{
loginID: $("#loginID").val(),
// some data here
},
url: 'http://mydomain.com/reg.php',
success: function(data){
alert('successfully.');
},
error: function(jqXHR, textStatus){
alert("Error: " + textStatus);
}
});
return false;
});
});
you can use return false.It will stop the execution
<form onSubmit="validatdeForm();"></form>
function validatdeForm()
{
//here return true if validation passed otherwise return false
}
or
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
it should be something like below. return false stop execution of script when error is there.
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
else
{
return true;
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
else
{
return true;
}
return true;
} // end of #validation
Design your validation function as below,
function validation()
{
var isValid = true;
if(field validation fail)
{
isValid = false;
}
else if(field validation fail)
{
isValid = false;
}
return isValid;
}
basic idea behind code is to returning false whenever your validation fails.
To make a proper form validation, I will suggest you go about doing it in a more organized way. It is easier to debug. Try this:
var validation = {
// Checking your login ID
'loginID' : function() {
// Login ID validation code here...
// If a validation fails set validation.errors = true;
// Additionally you can have a validation.idError that contains
// some error message for an id error.
},
// Checking your password
'loginPW' : function() {
// Password validation code here...
// If a validation fails set validation.errors = true;
// As with id, you can have a validation.pwError that contains
// some error message for a password error.
},
'sendRequest' : function () {
if(!validation.errors) {
// Code for whatever you want to do at form submit.
}
}
};
$('#test').click(function(){
validation.errors = false;
validation.loginID();
validation.loginPW();
validation.sendRequest();
return false;
});
function validateimage() { if($("#photo").val() !== '' ) {
var extensions = new Array("jpg","jpeg","gif","png","bmp");
var image_file = document.form_useradd.photo.value;
var image_length = document.form_useradd.photo.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert(" Upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
//$("#error-innertxt_photo").show().fadeOut(5000);
//$("#error-innertxt_photo").html('Enter valid file type');
//$("#photo").focus();
return false;
}
hi i am new enough to JavaScript and am wonder how to send details in email after validation ,heres my code
<script type="text/javascript">
var compName=false;
var compContry=false;
var compsub=false;
var compphone=false;
var compemail=false;
function validate_form(form)
{
if(compName)
{
document.getElementById('country').focus();
compName=true;
if(compContry)
{
document.getElementById('subject').focus();
compContry=true;
if(compsub)
{
document.getElementById('Phone').focus();
compsub=true;
if(compphone)
{
document.getElementById('email').focus();
compphone=true;
if(compemail)
{
//I just use alert to show it works.
alert("Your Details Are Sent ");
compemail=true;
}
else
{
document.getElementById('email').focus();
compemail=false;
}
}
else
{
document.getElementById('Phone').focus();
compphone=false;
}
}
else
{
document.getElementById('subject').focus();
compsub=false;
}
}
else
{
document.getElementById('country').focus();
compContry=false;
}
}
else
{
document.getElementById('username').focus();
compName=false;
}
}
You need some kind of server-side scripting to send emails.
After it passes validation you can submit your form like this
document.formname.submit();
in your case, this goes at the end of your function
if (comP... == true) {
form.submit();
}
you can add return false; after each validation if you are using cutom js
for example
var first_name = $("#first_name");
if(!$.trim(first_name.val()).length) {
first_name.closest('.form-group').removeClass('has-success').addClass('has-error');
return false;
}else{
first_name.closest('.form-group').removeClass('has-error').addClass('has-success');
}
return false will stop the submit button to proceed until the form is not filled.
freelancer