How do I display a popup error/success message when needed? - javascript

This is a javascript code in the HTML file, there is also a mail.php file.
Main:
I'm trying to create an alert function using "SweetAlert".
I want the error message to show up when the form is not validated and the success message when it is (email sent).
Extra:
When the form is validated and the success message shows, the page reloads. Can the page reload only when I click on the "OK" button in the popup?
<form class="contact100-form validate-form alert" action="mail.php" method="POST">
<span class="contact100-form-title">
Contact
</span>
<div class="wrap-input100 rs1-wrap-input100 validate-input" data-validate="Name is required">
<span class="label-input100">Your Name</span>
<input class="input100" type="text" name="name" placeholder="Enter your name">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 rs1-wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<span class="label-input100">Email</span>
<input class="input100" type="text" name="email" placeholder="Enter your email addess">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Message is required">
<span class="label-input100">Message</span>
<textarea class="input100" name="message" placeholder="Your message here..."></textarea>
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<button class="contact100-form-btn">
<span>
Send
<i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i>
</span>
</button>
</div>
</form>
$('.alert').on('submit', function validateForm() {
var name = document.forms["Form"]["name"].value;
var email = document.forms["Form"]["email"].value;
var message = document.forms["Form"]["message"].value;
if (name == "" || email== "" || message == "" ) {
swal("Great!", "We'll get back to you soon!", "success");
swal("Oops!", "Fill the blanks correctly!", "error" );
}
});
Right now, I'm getting an error message popup when the form is both not filled (not validated) and filled (validated form is submitted and I received the email).

This is because you have both the alerts in the same block.
Try this:
if (name == "" || email== "" || message == "" ) {
swal("Oops!", "Fill the blanks correctly!", "error" );
}
else
swal("Great!", "We'll get back to you soon!", "success");
As, I see your code, there's no mention of "Form" in there..
Edit your code with this..
<form class="contact100-form validate-form alert" name="Form" ..then the rest of code

SweetAlert uses promises to keep track of how the user interacts with the alert.
If the user clicks the confirm button, the promise resolves to true. If the alert is dismissed (by clicking outside of it), the promise resolves to null.
swal("Great!", "We'll get back to you soon!", "success")
.then((value) => {
if(!value) {
return false;
}
});

Related

Redirect to another HTML page after successfull login attempt | with JS

I have created a login form. I want a JS code that:
If the information on the login page i.e Username and Login is correct, It will proceed to another HTML page.
Simply, I want the page to redirect to another page after successfull login attempt. | With JS
I dont want any PHP or MySql code.
I have tried this code but this doesnt works. On wrong information, it says Invalid information. But on correct info, it refreshes the page and there a ? is visible at te end of the url:
Html:
<form id="form" action="" method="GET">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" id="email" class="form-control" aria-describedby="emailHelp" >
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit" class="btn btn-outline-success btn-lg shadow" onClick="auth()">Submit</button>
</form>
JavaScript:
function auth() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
location = location['href'];
// alert("You Are a ADMIN");
} else {
alert("Invalid information");
return;
}
}
I have also used:
window.location.replace("upload.html");
instead of:
location = location['href'];
But still does not works.
A couple of things here. One you're doing a GET with your form rather than doing a POST. You should change that. Second, on your JavaScript call for auth you should pass the event parameter so that the default action of the form will be stopped. Third, you should be using a relative path for your URL within your redirect. Last, You should do a window.redirect() to simulate an HTTP redirect when the function executes.
Here is the code with the updates:
<form id="form" action="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email"
id="email"
class="form-control"
aria-describedby="emailHelp" >
<small id="emailHelp"
class="form-text text-muted">
We'll never share your email with anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" id="password" class="form-control" >
</div>
<button type="submit"
class="btn btn-outline-success btn-lg shadow"
onClick="auth(event)">Submit</button>
</form>
<script>
function auth(event) {
event.preventDefault();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if (email === "admin#gmail.com" && password === "user") {
window.location.replace("/upload.html");
} else {
alert("Invalid information");
return;
}
}
</script>

Sweetalert PoP-up message when fields are field is not working

I had a question about Sweetalert a week ago. Then I got an answer which helped me, but unfortunately, it is still not working. I wanted a Sweetalert pop-up message (success) when the user hits the submit button, but only if the fields are filled. I do not know what the problem is. Currently, nothing happens when the user hits the button.
Here is my code:
function Sweetalert1(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var email = document.getElementById("email").value;
if (name != " " && message != " " && email != " "){
Swal.fire(
'Köszönjük!',
'Megkaptuk a leveledet és hamarosan válaszolunk!',
'success',
)}
}
And the part of the HTML:
<form role="form" id="contactForm" action="contact.php" method="post">
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Név</label>
<input class="form-control" id="name" name="name" type="text" placeholder="Név" required="required" data-validation-required-message="Kérlek add meg a neved!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Email Cím</label>
<input class="form-control" id="email" type="email" name="email" placeholder="Email" required="required" data-validation-required-message="Kérlek add meg az Email címed!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Üzenet</label>
<textarea class="form-control" id="message" rows="5" placeholder="Üzenet" name="message" required data-validation-required-message="Kérlek írd be az üzeneted!"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div id="success"></div>
<div class="form-group">
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
</div>
</form>
I can't see where the button was fired
On this line,
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
You have at least two options to fire the button
1st
You can change the line to this
<button name="submit" type="submit" class="btn" id="sendMessageButton" onclick="Sweetalert1()">Küldés</button>
2nd
You can add this to your javascript section
$("#sendMessageButton").click(function(){
Sweetalert1();
});
3rd
You can use the form's on-submit event
$("form").submit(function(){
Sweetalert1();
});
When this is done, modify your condition to
if (name !== "" && message !== "" && email !== "")
OR
if (name.trim() && message.trim() && email.trim())
your condition is not right, try doing this:
if (name && message && email)
{
// Code
}
An empty field isn't equal to a space (" "), it is equal to an empty string (""). So, you need to check if the fields equal an empty string, not a field with a space:
if (name != "" && message != "" && email != "") {
// code...
}
However, if you want to treat fields which have no text in them (and just spaces) as invalid as well, you can add the .trim() method to your name, message and email variables. By using trim you can turn inputs such as
" " into "", which will then be treated as an invalid input:
if (name.trim() != "" && message.trim() != "" && email.trim() != "") {
// code...
}
As an empty string is considered falsey (ie "" == false) you don't need to check whether you're input equals an empty string and instead can just check if x.trim() evaluates to true like so:
if (name.trim() && message.trim() && email.trim()) {
// code...
}

jquery fadeIn and fadeOut not working before click

i have one form like this.
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
and i call one .js file for it is.
$(document).ready(function(){
$('#send_message').click(function(e){
//Stop form submission & check the validation
e.preventDefault();
// Variable declaration
var error = false;
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#phone').val();
var message = $('#message').val();
// Form field validation
if(name.length == 0){
var error = true;
$('#name_error').fadeIn(500);
}else{
$('#name_error').fadeOut(500);
}
if(email.length == 0 || email.indexOf('#') == '-1'){
var error = true;
$('#email_error').fadeIn(500);
}else{
$('#email_error').fadeOut(500);
}
if(subject.length == 0){
var error = true;
$('#phone_error').fadeIn(500);
}else{
$('#phone_error').fadeOut(500);
}
if(message.length == 0){
var error = true;
$('#message_error').fadeIn(500);
}else{
$('#message_error').fadeOut(500);
}
// If there is no validation error, next to process the mail function
if(error == false){
// Disable submit button just after the form processed 1st time successfully.
$('#send_message').attr({'disabled' : 'true', 'value' : 'Sending...' });
/* Post Ajax function of jQuery to get all the data from the submission of the form as soon as the form sends the values to email.php*/
$.post("contact-post.php", $("#contact_form").serialize(),function(result){
//Check the result set from email.php file.
if(result == 'sent'){
//If the email is sent successfully, remove the submit button
$('#submit').remove();
//Display the success message
$('#mail_success').fadeIn(500);
}else{
//Display the error message
$('#mail_fail').fadeIn(500);
// Enable the submit button again
$('#send_message').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
and one contact-post.php file is.
<?php
include('config.php');
if (isset($_POST['submit'])) {
$name=$_POST['name'];
$mail=$_POST['email'];
$phone=$_POST['phone'];
$msg=$_POST['message'];
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
test_input($name);
$query="INSERT INTO `inquiry` (id,name,contact,email,query) values ('','$name','$phone','$mail','$msg')";
$qur=mysql_query($query);
if ($qur) {
echo 'sent';
}
else {
echo 'failed';
}
}
?>
my problem is when i refresh page it's displaying like this.
i want that all message should not display before clicking submit button.please help me.
Update (adding snippet) :
.error , .success
{
display:none;
}
<form method="post" action="contact-post.php" id="contact_form" name="contactForm">
<div class="left_form">
<div>
<span><label>NAME</label></span>
<div id='name_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="name" id="name" type="text" class="textbox"></span>
</div>
<div>
<span><label>E-MAIL</label></span>
<div id='email_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="email" id="email" type="text" class="textbox" required></span>
</div>
<div>
<span><label>PHONE</label></span>
<div id='phone_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><input name="phone" id="phone" type="text" class="textbox"></span>
</div>
</div>
<div class="right_form">
<div>
<span><label>SUBJECT</label></span>
<div id='message_error' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Please enter your name.</div>
<span><textarea name="message" id="message" required> </textarea></span>
</div>
<div id='mail_success' class='success' style="background-color:#BFD6BF;text-align:center;margin-bottom:5px;">Your message has been sent successfully.</div>
<div id='mail_fail' class='error' style="background-color:#FFBCBB;text-align:center;margin-bottom:5px;">Sorry, error occured this time sending your message.</div>
<div id="submit">
<span><input type="submit" id="send_message" name="submit" value="Submit" class="myButton"></span>
</div>
</div>
</form>
You can do one of the following :
Set the error and success classes display to none, since they will be displayed using the fadeIn function.
.error , .success
{
display:none;
}
Or
You can hide the <div>s with jQuery on load as follows :
$(document).ready(function(){
$('.error , .success').hide();
.....
});
I guess the first solution would be a better approach since the elements will not view at all since CSS loads before JS (assuming that this is the order you are loading your files with), while in the second approach the elements will be visible until jQuery loads and hides them.
Add a style as below to hide the error/success messages.
#mail_fail, #mail_success{
display : none;
}

Form submission causing 'Maximum call stack size exceeded'

I've created a form that is used to review a person on a website, however when the form is submitted nothing happens and console is showing a 'Maximum Call Stack Exceeded'. Hopefully someone can help point out the error in my code stopping this from working. Here is the form code:
<form id="fReviewMe" method="post" action="/process/review-p.cfm" enctype="multipart/form-data" style="display:none">
<label style="padding-top:10px"><i class="fa fa-asterisk magenta"></i> Your Name:</label>
<input type="text" name="uname" id="uname" class="span8" placeholder="Please tell us your name">
<label><i class="fa fa-asterisk magenta"></i> Your Business Name:</label>
<input type="text" name="business" id="business" class="span8" placeholder="Please tell us your business name">
<label><i class="fa fa-asterisk magenta"></i> Your Review:</label>
<textarea name="reviewmsg" id="reviewmsg" class="span8" rows="8" placeholder="Please add your review in here"></textarea>
<!--- form errors --->
<div id="dFormErrors" class="row" style="display:none;padding-bottom:20px;">
<span id="sEMessage" class="pull-right"></span>
<i class="fa fa-asterisk magenta pull-right"></i>
</div>
<!--- form buttons --->
<div id="dButtonsReviewForm" class="row">
<a onClick="checkForm()" name="submit" class="cta pull-right">Submit</a>
Cancel
</div>
<!--- form saving --->
<div id="dSavingReviewForm" style="display:none">
<span class="pull-right hibuBtn" style="cursor:wait"><i class="fa fa-spinner fa-spin"></i> Saving</span>
</div>
Here is the JS code:
/* intercept submit event */
$( "#fReviewMe" ).submit(function(event) {
checkForm();
event.preventDefault();
});
/* form validation */
function checkForm(){
var errors = 0;
var cuname = $('#uname').val();
var ccompany = $('#business').val()
var creview = $('#reviewmsg').val()
var cstars = $('#rStar').val()
var eMessage = "";
$('#dFormErrors').hide();
$('input').removeClass('validFalse');
$('textarea').removeClass('validFalse');
if ($('#tnc').is(':checked')) {
}
else{
eMessage = "Please tick to accepts out terms and conditions";
errors++;
}
if(cstars.length < 1){
$("input").blur();
$("textarea").blur();
eMessage = "Please choose a star rating";
errors++;
}
if(creview.length < 1){
$('#reviewmsg').focus();
$('#reviewmsg').addClass('validFalse');
eMessage = "Please add your review";
errors++;
}
else{
$('#reviewmsg').addClass('validTrue');
}
if(ccompany.length < 1){
$('#business').focus();
$('#business').addClass('validFalse');
eMessage = "Please tell us your business name";
errors++;
}
else{
$('#business').addClass('validTrue');
}
if(cuname.length < 1){
$('#uname').focus();
$('#uname').addClass('validFalse');
eMessage = "Please tell us your name";
errors++;
}
else{
$('#uname').addClass('validTrue');
}
/* check errors and submit */
if(errors > 0){
$('#dFormErrors').slideDown();
$('#sEMessage').html(eMessage)
}
else{
$('#dButtonsReviewForm').hide();
$('#dSavingReviewForm').show();
$('#fReviewMe').submit();
}
}
Thanks in advance
Replace $('#fReviewMe').submit(); with:
$('#fReviewMe')[0].submit();
calling DOM node method submit to avoid submit jQuery handler 'loop'.

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

Categories

Resources