Jquery/php form have to click Submit Twice Why? - javascript

I have a simple form with jquery and php
whenever someone clicks the submit button they have to click it twice
Heres my jQuery
$('#submit_btn').on('click', function(){
var post_data, proceed, user_email, user_message, user_name, user_phone;
user_name = $("input[name=name]").val();
user_email = $("input[name=email]").val();
user_phone = $("input[name=phone]").val();
user_message = $("textarea[name=message]").val();
proceed = true;
if (user_name === "") {
$("input[name=name]").css("border-color", "red");
proceed = false;
}
if (user_email === "") {
$("input[name=email]").css("border-color", "red");
proceed = false;
}
if (user_phone === "") {
$("input[name=phone]").css("border-color", "red");
proceed = false;
}
if (user_message === "") {
$("textarea[name=message]").css("border-color", "red");
proceed = false;
}
if (proceed) {
post_data = {
userName: user_name,
userEmail: user_email,
userPhone: user_phone,
userMessage: user_message
};
$.post("contact_me_test.php", post_data, (function(response) {
var output;
if (response.type === "error") {
output = "<div class=\"error\">" + response.text + "</div>";
} else {
output = "<div class=\"success\">" + response.text + "</div>";
$('#contact-form-container').fadeOut(function(e){
$('#form-success-message').fadeIn();
});
$("#contact_form input").val("");
$("#contact_form textarea").val("");
}
$("#result").hide().html(output).slideDown();
}), "json");
}
});
Heres my jQuery
Is there something that requires to thing to be pressed twice here? I looked around online for hours and some people were saying you need to take the validation out of it but I've tried that and i get the same results.
Everything regarding the form is working fine the only thing is that you have to click TWICE

Try with this code:
$('#submit_btn').on('click', function(evt){
evt.preventDefault();
... //Rest of code
}

Related

Open new tab onclick JS event using handler ashx

I have a login button with onclick event...onclick = "login();"
I successfully logged in ...but I wanted to open new tab instead.
This is my javascript:
login = function() {
if ($("#UserName").val().length == 0) {
return;
}
if ($("#Password").val().length == 0) {
return;
}
var logindata = new Object();
logindata.UserName = $("#UserName").val();
logindata.Password = $("#Password").val();
locustraxx.showLoading("loginformDiv");
locustraxx.doAjaxPostback('//example.com/LoginHandler.ashx', logindata, null, null,
function(data, textStatus, jqXHR) {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (data.success == true) {
if ($("#Remember").is(':checked')) {
$.cookie('remember', $("#UserName").val() + '|' + $("#Password").val(), {
expires: 36500,
path: '/'
});
}
var retUrl = $.QueryString("ReturnUrl");
if (retUrl == undefined || retUrl == null) {
window.location.replace(data.data, '_blank');
} else {
window.location.href = decodeURIComponent(retUrl).replace(/\~~/g, ".");
}
if (isChrome) {
// clearCookies();
}
return false;
} else {
alert(data.message);
$("#UserName").focus();
}
}, null,
function() {
login.hideLoading("loginformDiv");
});
}
I tried _blank... window open, but to no avail
Could you please specify better what you have tried so far in theory you should be OK with:
window.open('https://www.google.com', '_blank');
If It isn’t working please specify the error output of the console.
There is also a known issue in which the browser opens a new window instead of a new tab, but that has to do with the user preferences, nothing to do about that. See here.

How to successfully call the submit when all validations are true

I have created a validation in javascript which detect if there's an empty field and if there's none then it will now insert into database which I use a PHP code.
But it does nothing I'm having trouble inserting into database, I think because I put e.preventDefault(), I put the e.preventDefault() so it will not reload and show the validation messages that I created.
(function() {
document.querySelector('#addForm').onsubmit = function (e) {
e.preventDefault();
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
//Check empty input fields
if(!document.querySelector('#name').value){
name.classList.add('is-invalid');
}else{
name.classList.remove('is-invalid');
}
if(!document.querySelector('#age').value)
{
age.classList.add('is-invalid');
}else{
age.classList.remove('is-invalid');
}
if(!document.querySelector('#email').value){
email.classList.add('is-invalid');
}else{
email.classList.remove('is-invalid');
}
}
})();
You should only e.preventDefault() if any of the inputs are empty then, example updated:
document.querySelector('#addForm').onsubmit = function(e) {
const name = document.querySelector('#name');
const age = document.querySelector('#age');
const email = document.querySelector('#email');
let formIsInvalid = false;
//Check empty input fields
if (!name.value) {
name.classList.add('is-invalid');
formIsInvalid = true;
} else {
name.classList.remove('is-invalid');
}
if (!age.value) {
age.classList.add('is-invalid');
formIsInvalid = true;
} else {
age.classList.remove('is-invalid');
}
if (!email.value) {
email.classList.add('is-invalid');
formIsInvalid = true;
} else {
email.classList.remove('is-invalid');
}
if (formIsInvalid) {
e.preventDefault();
}
}
You should append AJAX request to send values to the server
var th = $(this);
$.ajax({
type: "POST",
url: "handler.php", //Change
data: th.serialize()
}).done(function() {
alert("Thank you!");
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});

How to return false from a main function after an ajax callback?

I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.

Login using Json

I am trying to develop a login process using json.
My problem is that when I make many login attempts , parameters are not overriden but concatenated.
Below is the code I'm writing.
I do not see where the problem is.
Thank you in advance .
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function() {
var json = this.responseText;
Titanium.API.info("step 1 done");
var response = JSON.parse(json);
if (response.status == true) {
Titanium.App.Properties.setString("key", response.key);
alert("Success");
} else {
alert("Email or password wrong");
}
};
function doConnVerif() {
if ($.email.value != '' && $.password.value != '') {
loginReq.open("POST", "URL");
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
} else {
alert("Enter email and password");
}
}
By your question I can't grasp the full aspect of the problem, but definitely a good idea would be only allow one login attempt at a time.
Something like:
var pendingRequest = false;
// ...
if(!pendingRequest) {
loginReq.send({
'email' : $.email.value ,
'password' : $.password.value
});
pendingRequest = true
}
// ...
loginReq.onload = function() {
pendingRequest = false
// ...

How to stop execution when form validation in javascript

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;
}

Categories

Resources