js validation only runs once - javascript

I'm having an issue with the code below where if I put an invalid email address in it will properly show the signUpWarning alert the first time but if I close that box and try the same invalid email it won't pop back up. Any ideas?
$(document).ready(function() {
//if submit button is clicked
$('#submit_btn').click(function(e) {
e.preventDefault();
var email = $('#email').val();
if (!is_valid_email(email)){
$("#signUpWarning").show();
}else{
$.ajax({
url: "process.php",
type: "post",
data: "email=" + email,
success: function() {
$("#signUpWarning").hide();
$("#signUpAlert").show();
}
});
}
});
});
function is_valid_email (email)
{
return /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}
The code for the alert box is:
<div class="alert alert-block alert-error hide" id="signUpWarning"><!--Use: $("#signUpWarning").show(); to show this alert-->
<a class="close" data-dismiss="alert">×</a>
<h5 class="alert-heading">Sorry!</h5> Your e-mail address was not valid, please try again.
</div>

Check that you're not removing the element from the DOM when closing the alert.
console.log($("#signUpWarning")); before the $("#signUpWarning").show(); should help determine if that's what's happening.

Related

Hide a card after confirming in bootstrap modal on AJAX success

My delete page contains multiple post with delete button, when delete button is pressed bootstrap bootstrap modal opens and will ask for confirmation are you sure you want to delete post ? YES : NO
when YES button is pressed .click(function (e){....} sends AJAX request to database, if ajax return success that paticular card should be hidden
so i tried with following code
$(document).ready(function () {
$("#confirm").click(function (e) {
e.preventDefault();
var that = this;
const act = $(this).attr('data-act');
const para = $(this).attr('data-para');
const hash = $(this).attr('data-hash');
$.ajax({
url: '/include/ajax/mark_sold.php', // Call delete.php to update the database
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
$(that).closest('div.card').hide(); //to hide div after ajax success
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
return false;
});
HTML
<div class="card border-0 small col-lg-3 col-md-2 col-6 mb-2 px-1">
<img class="card-img-top rounded-0" src="/upload/" alt="Card image cap">
<div class="card-body pb-0 pt-2 px-0">
<h6 class="card-title text-dark text-truncate">title</h6>
</div>
<button data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-block btn-sm modalopen" data-hash="6d8ce77d206011027297b693be999704" data-para="A4IxzuRP8ATv">delete</button>
</div>
How do i hide card after confirming in modal
The problem in your code is, that your variable "that" is not referring to the delete button, but to the confirm button of the dialog, therefore you can't use closest() function. At this point, you should use some specific identification for your card/delete button. For example:
$('button[data-hash="'+hash+'"]') .closest('div.card').hide();
Another point that I don't see in your code is the transfer of data variables (act, para, hash) to the dialog confirm button. For example your code $(this).attr('data-hash') can't reach value from the delete button because $(this) refers to the dialog confirm button. The solution to this problem is to pass a unique identifier to the dialog button.
$(".deleteBtn").on('click',function(){ //Add on click event to all delete buttons
$("#confirm").data("hash",$(this).data("hash")); //Pass hash value to dialog confirm button
});
$("#confirm").click(function (e) {
e.preventDefault();
var delBtn = $('button[data-hash="'+$(this).data("hash")+'"]'); //Get specific delete button element by passed hash value
const act = delBtn.attr('data-act'); //Get data variables from the delete button element
const para = delBtn.attr('data-para');
const hash = $(this).data("hash");
$.ajax({
url: '/include/ajax/mark_sold.php',
method: 'POST',
data: {action: act, para: para, hash: hash},
cache: false,
success: function (data, status) {
$("#fetched").html(data);
$('#myModal').modal('hide');
delBtn.closest('div.card').hide(); //Find closest .card element to the specified delete button
},
error: function (xhr, statusText, error) {
$("#fetched").show();
$("#confirmButton").hide();
}
});
});
Don't forget to add .deleteBtn class to your delete buttons.
Hope it helps.

Ajax Post Data and return with error message

i currently have the code below that submits form data from a bunch of dynamic forms this is working well and is returning a notification with a success or failure and inserting it into the div #info however when the error or success is shown on the page the only way to get rid of the notification is to refresh or navigate to another page
<script>
$(function() {
$(document).on('submit', 'form.frm_details', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if (data.status == '1') {
$('#info').addClass('alert alert-success alert-styled-left alert-arrow-left alert-bordered').html(data.message);
$('.my-modals').modal('hide');
document.getElementById('frm_details0').reset();
}
}
});
});
});
</script>
so my question is how can i make it so you click a link or a an x button on the right hand side of the notification window to close the or hide the div
i have attached a picture copy of the notification window and the only code on the page besides the script below is
As Per comments:
<script>
$(function() {
$(document).on('submit', 'form.frm_details', function(event) {
event.preventDefault();
$.ajax({
url: '/limitless/functions2.php',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if (data.status == '1') {
$('#info').addClass('alert alert-success alert-styled-left alert-arrow-left alert-bordered').html(data.message);
$('.my-modals').modal('hide');
document.getElementById('frm_details0').reset();
}
}
});
});
//preferably anchor tag
$('.some-close-element').click(function(e)
{
e.preventDefault();
$(this).parent().hide();
});
});
</script>
This makes the assumption your adding an anchor tag inside info alert box which ultimately closes the alert box.
You can hide notification after some time interval on get response from ajax:
if (data.status == '1') {
$('#info').addClass('alert alert-success alert-styled-left alert-arrow-left alert-bordered').html(data.message);
setTimeout( function(){
$('#info').hide();} ,
3000);
//or
$("#info").delay(4000).hide();
$('.my-modals').modal('hide');
document.getElementById('frm_details0').reset();
}
After more research on this site i was going about the alerts all wrong i should be dismissing the alert as per the discussion here
Bootstrap successful alert in updating record Ajax
however after thoroughly reading my and trial and error my solution is the below
$('#info').html('<div class="alert alert-danger alert-styled-left alert-arrow-left alert-bordered">' + data.message + '<button type="button" class="close" data-dismiss="alert" >×</button></div>');

How to Add reCAPTCHA to Forms

I'm trying to add reCaptcha to my Form, but it does't go further than validation. Please help!
I've added the key and I've added the path to /php/recaptachalib.php
but for some reason it doesn't work, when I type captcha or mistype captcha, when I click submit, nothing happens.
reCAPTCHA
<form id="another_form" name="another_form" method="post">
<input type="submit" value="Submit Another Form" />
</form>
<div id="recaptchaModal" title="reCAPTCHA" style="display:none;">
<p>Please fill out this reCAPTCHA to submit this form.</p>
<div id="recaptcha_block"></div>
</div>
<script>
$('form').on('submit', function(e){
e.preventDefault();
var formID = e.currentTarget.id;
$("#recaptchaModal").dialog({
modal: true,
resizable: false,
width: 400,
open: function(e, ui){
Recaptcha.create("your_recaptcha_public_key",
"recaptcha_block",
{
theme: "red",
callback: Recaptcha.focus_resonse_field
}
);
},
close: function(e, ui){
Recaptcha.destroy();
},
buttons: {
"Validate reCAPTCHA": function(){
$.ajax({
url: "/url/to/verify/recaptcha",
type: 'post',
data: {
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response(),
additional_data: here
},
success: function(data){
if(data != "success"){
alert("The reCAPTCHA wasn't entered correctly. Please try again.");
Recaptcha.reload();
}
else{
//-- submit your form with AJAX + MVC-style
$.ajax({
url: "/your/submission/url/"+formID,
type: "post",
data: $('#'+formID).serialize(),
success: function(data){
//-- forward user to your thank you page
window.location.href = '/url/to/your/thank/you/page/'+formID;
}
});
}
}
});
},
Cancel: function(){
$(this).dialog("close");
}
}
});
});
</script>
</body>
Captcha is a script that prevents bots from spamming a form i.e. it validates that the agent is a real Human. Secondly, it act as a training for Google’s Machine learning by Identifying Objects in Images
Step 1) Go to https://www.google.com/recaptcha/admin#list.
Step 2) Choose the type of Captcha you want to add.
Step 3) Select the Domain for its usage. For example, indiaedge.in
Step 4) Click Register .
Step 5) Now you will see your site key and secret key .
Step 6) Paste the script tag in the head section of your page.
How to add Captcha in Login Form

How to prevent form resubmission alert on refresh?

I have a website with a footer in which there's a small form. There's only two things in this form: an input textbox for taking emails, and a submit button.
When user presses the Submit button, no redirection takes place, and instead an AJAX call is done to add the email to a Database table, and show the appropriate message using jQuery slideDown().
The problem is that even though no redirection to another page actually happens, still when I refresh the page sometimes, I get a browser alert that this may resubmit data. I doesn't always come, only sometimes. Don't know why.
How can I completely stop this error from coming ?
JSFiddle (See note below): http://jsfiddle.net/ahmadka/7cZZY/1/
Please note that because the footer_subscribe.php file is unaccessible from within JSFiddle, I don't get the form resubmission error here .. However the error does sometimes show up when you refresh the original actual page:
Actual page (Form is in footer section at the bottom of page): http://bit.ly/15eb2Cx
HTML Code:
<section class="subscribe">
<form class="form-wrapper cf" method="post">
<input name="email" placeholder="Enter your email here..." />
<button id="submitBtn" type="submit">Subscribe</button>
</form>
<p></p>
</section>
JavaScript Code:
$(function () {
$("#submitBtn").click(function (event) {
event.preventDefault();
event.returnValue = false;
var inputEmail = $(".subscribe input[name=email]").val();
var inputEmailTrimmed = $.trim(inputEmail);
if (inputEmail == "") {
$(".subscribe p").html("Please enter an email address.").slideDown();
} else if (inputEmailTrimmed == "" && inputEmail != inputEmailTrimmed) {
$(".subscribe p").html("Simply entering spaces won't cut it :)").slideDown();
} else {
$.ajax({
type: "POST",
url: "footer_subscribe.php",
data: {
email: inputEmail
},
success: function (data) {
if (data == "successful") {
$(".subscribe p").html("Thanks for your interest!").slideDown();
} else if (data == "already_subscribed") {
$(".subscribe p").html("This email is already subscribed.").slideDown();
} else if (data == "invalid_email") {
$(".subscribe p").html("This email is invalid.").slideDown();
} else {
$(".subscribe p").html("Something went wrong. Please try again later.").slideDown();
}
},
error: function () {
$(".subscribe p").html("Subscription is not available.").slideDown();
}
});
}
});
});

Disable form inputs after ajax submission

I have a form that submits via Ajax. After the user sends the form, the text changes displaying the form was sent successfully and then shows the form filled out. I want to display the form but I don't want them to re-submit the form so I want to disable the inputs as well as the submit button. I tried adding: $('#submit_btn').className +=" disabled" to the ajax script but it just made the page refresh without submitting anything.
The ajax script is as follows:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
var email = $("inputemail").val();
var phone = $("inputphone").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://www.green-panda.com/website/panda/webParts/contact-form.php",
data: dataString,
success: function() {
$('#myModalLabel').html("<h3 class='text-success' id='myModalLabel'>Contact Form Submitted!</h3>")
$('#myModalSmall').html("<p class='muted'>Your submiessions are below. We will be contacting you soon, you may now close this window.</p>")
$('#submit_btn').className +=" disabled"
.hide()
.fadeIn(1500, function() {
$('#message').append("<i class='icon-ok icon-white'></i>");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
How could I possibly disable the inputs and button after a successful form submission?
http://jsfiddle.net/gY9xS/
Actually it's a lot simpler than what you're trying to do, you don't need to disable the inputs, simply cancel the submit after the ajax request:
$('form').submit(function(){
return false;
});
Put it inside the success handler of your ajax request.
If you want to disable the submit button, replace this wrong thing:
$('#submit_btn').className +=" disabled"
With:
$('#submit_btn').prop("disabled", true);
In my application, i just disabled the submit button and shows some progress message
function submitForm(formObj) {
// Validate form
// if (formObj.email.value === '') {
// alert('Please enter a email');
// return false;
// }
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
return true;
}
<form class="form-login" accept-charset="UTF-8"
method="POST" action="/login" onsubmit="return submitForm(this);">
......
<input type="submit" id="login-submit" name="submit" value="Log In">
</form>

Categories

Resources