i'm working on a email sending function on a project. here when i fill the form and after sending it the web site page getting refresh and showing white background page. i need to prevent that from the refreshing and submit the form. here i'l attach the codes and can someone tell me the answer for this question.
HTML code for form
<form class="form-vertical" onsubmit="return sendEmail();" id="tell_a_friend_form" method="post" action="index.php?route=product/product/tellaFriendEmail" enctype="multipart/form-data">
<div class="form-group ">
<label class="control-label ">Your Name <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="senders_name" name="sender_name" value="" class="form-control input-lg required" >
</div>
</div>
<div id="notify2" class="">
<div id="notification-text2" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label ">Your Email <span >* </span> </label><br>
<div class="form-group-default">
<input type="text" id="sender_email_ID" name="sender_email" value="" class="form-control input-lg" >
</div>
</div>
<div id="notify1" class="">
<div id="notification-text1" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div class="form-group ">
<label class="control-label">Your Friends' Email <span >* </span></label>
<p class="lineStyle">Enter one or more email addresses, separated by a comma.</p>
<div class="form-group-default">
<input type="text" value="" id="receiver_email" class="form-control required" name="receivers_email" >
</div>
</div>
<div id="notify" class="">
<div id="notification-text" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<div >
<label domainsclass="control-label ">Add a personal message below (Optional) <br></label>
<div class="form-group-default">
<textarea type="text" id="tell_a_friend_message" name="tell_a_friend_message" class="form-control" rows="10" col="100" style=" width: 330px; height: 100px;"></textarea>
</div>
</div>
<div id="notify3" class="">
<div id="notification-text3" class="xs-m-t-10 fs-12"></div>
<!--<button type="button" class ="close" id="noti-hide">×</button>-->
</div>
<input type="hidden" name="product_url" id="product_url_field" value="">
<div class="p-t-15 p-b-20 pull-right">
<button id="send_mail_button" class="btn btn-rounded btn-rounded-fl-gold text-uppercase" name="submit" onclick="return sendEmail();" >Send</button>
<button id="cancel_email_form" class="btn btn-rounded btn-rounded-gold text-uppercase btn-margin-left" data-dismiss="modal" aria-hidden="true" >Cancel</button>
</div>
javascript code:
<script>
function sendEmail() {
document.getElementById('product_url_field').value = window.location.href
var emailpattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var receivers_email = $("#receiver_email").val();
var sender_email = $("#sender_email_ID").val();
var sender_name = $("#senders_name").val();
var email_pathname = window.location.pathname;
var product_url = window.location.href;
if (receivers_email == '') {
$('#notify').removeClass().addClass("alert-danger");
$('#notification-text').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text').show();
setTimeout(function() {
$('#notification-text').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(receivers_email);
}
if(sender_name == ''){
$('#notify2').removeClass().addClass("alert-danger");
$('#notification-text2').empty().html("please fill the name");
$('#notification-text2').show();
setTimeout(function() {
$('#notification-text2').fadeOut('slow');
}, 10000);
return false;
}
if (sender_email == '') {
$('#notify1').removeClass().addClass("alert-danger");
$('#notification-text1').empty().html("Invalid e-mail or fill the email address correctly");
$('#notification-text1').show();
setTimeout(function() {
$('#notification-text1').fadeOut('slow');
}, 10000);
return false;
}
else {
!emailpattern.test(sender_email);
}
$('#notify3').removeClass().addClass("alert-success");
$('#sender_email').val('');
$('#notification-text3').empty().html("Email has sent successfully");
$('#notification-text3').show();
setTimeout(function() {
$('#notification-text3').fadeOut('slow');
}, 10000);
return true;
}
</script>
Controller php class:
public function tellaFriendEmail(){
if (isset($_POST['submit'])) {
$receiver_email = $_POST['receivers_email'];
$name = $_POST['sender_name'];
$email = $_POST['sender_email'];
$message = $_POST['tell_a_friend_message'];
$products_url = $_POST['product_url'];
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($receiver_email);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender("Waltersbay");
$mail->setSubject($name.' '.'wants you to checkout this product from waltersbay.com');
if ($message !=''){
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'.'<br/> Thank you, <br/> ');
}
else{
$mail->setHtml('Hi Dear,<br/> please checkout the following product that'.' '.$name.' '.'wanted you to see.'.' '.'we hope that you will like it !!!!<br/>'.$products_url.'<br/>'/*.'<br/> Here is a little message from your friend:<br/>'.$message.'<br/>'*/.'<br/> Thank you, <br/> ');
}
$mail->send();
}
else{
header('location : tella_friend.tpl');
}
}
}
Put a hidden input in your form. before submitting in your js, fill it with a new key according to time.
in your php file check if key is duplicate or not? or even if its filled?
Because js fill this input after clicking the submit button, every time you submit your form you have a new key! If you refresh the form, you're gonna send the previous value again.
For your problem then best practice recommended is to use jquery ajax requests.
Firstly if you pretend to use "submit" element then do following,
$(".form-vertical").submit(function(e) {
e.preventDefault();
//send ajax with your form data. Ample examples on SO already.
$.ajax(.....);
});
Other option we would recommend is to avoid using 'submit' behavior at first place for requirement you have.
1. Use button elements instead of submit element.
2. Attach click event on button. i.e. in your case 'send'.
3. On click, send ajax as described above. This will avoid doing things like onsubmit="return sendEmail();" you had to do.
4. Also following is not required as well,
$(".form-vertical").submit(function(e) {
e.preventDefault();
as it will be done as follows,
$("button#buttonId").click(function(e) {
// your ajax call.....
}
Related
I am new to Jquery but I have done a lot with html/php in the past. What I need to do is submit for data from within a popup modal, insert that into a mysql database on localhost and then open teh next popup via javascript. As redirecting to the php page does not allow you to load js, I have looked into using jquery to post the data to my phpfile, which will then insert the data and return a code to the jquery, which will then load the next popup if the post was succesful. I have tried different tutorials, but I just cannot get the code to work. Below is my index.php file, which contains the popup form and jquery code...
<div id="survey1" class="w3-modal">
<div class="w3-modal-content w3-animate-top w3-card-4">
<div class="w3-container w3-padding-16">
<div class="section-heading text-center">
<div class="col-md-12 col-xs-12">
<h1>BASIC <span>DETAILS</span></h1>
<p class="subheading">The basics of your business and your website.</p>
</div>
</div>
<form role="form" class="login-form" method="post" action="http://localhost/basic.php" id="basicForm">
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Full Name" aria-describedby="basic-addon1" name="name" id="name">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Email" aria-describedby="basic-addon1" name="email" id="email">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Business Name" aria-describedby="basic-addon1" name="bname" id="bname">
</div>
<div class="input-group form-group">
<span class="input-group-addon" id="basic-addon1"><i class="fas fa-envelope"></i></span>
<input type="text" class="form-control" placeholder="Business Type" aria-describedby="basic-addon1" name="btype" id="bemail">
</div>
<div id="response"></div>
<button class="btn" type="submit" id="submit1" name="submit1" style="width:40%; float: right;"></button>
</form>
<script>
$(document).ready(function(){
$('#basicForm').on('submit', function(e){
e.preventDefault();
$('#submit1').prop('disabled', true);
var name = $('#name').val();
var email = $('#email').val();
var bname = $('#bname').val();
var btype = $('#bemail').val();
if(name == '' || email == '' || bname == '' || btype == '')
{
$('#submit1').prop('disabled', false);
}
else
{
$.post(
'http://localhost/TDS/basic.php',
$('#basicForm').serialize(),
function(data)
{
$('form').triggered("reset");
$('#submit1').prop('disabled', false);
}
);
}
});
});
</script>
</div>
</div>
</div>
And this is my php insert file...
<?php
require('connection.php')
if(isset($_POST["name"]))
{
$name = mysqli_real_escape_string($con, $_POST["name"]);
$email = mysqli_real_escape_string($con, $_POST["email"]);
$bname = mysqli_real_escape_string($con, $_POST["bname"]);
$btype = mysqli_real_escape_string($con, $_POST["btype"]);
$insert_query = "INSERT INTO Details ('Name', 'Email', 'Business Name', 'Businesss
Type') VALUES ('".$name."', '".$email."', '".$bname."', '".$btype."')";
if(mysqli_query($con, $insert_query))
{
echo json_enchode(success => 1);
}
else
{
echo json_enchode(success => 0);
}
}
?>
Any help would be much appreciated!
The code itself is OK, but you need to load jQuery itself.
Put this somewhere in the beginning of your HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
(the tips on how to include jQuery see here: https://www.w3schools.com/jquery/jquery_get_started.asp)
Except this, the code worked for me:
- The form was submitted correctly;
- The PHP endpoint received the correct POST data;
The saving to DB I didn't check, but it looks OK.
Anyways, the PHP part is out of the scope of the question.
Also, a small issue is in the code itself: there's no such method as "$('form').triggered('reset');", use "$('form').trigger('reset');" instead.
I have two forms on a single page, one of them is a login form and the other is a register form (two tabs) and I want to check the the captchas, but when I click the check captcha from register form I can't login.
The login form:
HTML:
<div id="loginUserTab" class="tab-pane fade">
<form>
<div class="form-group login-width-100">
<label for="id_number" class="m-rtl-label"><span class="requiredMark">*</span>passport number:</label>
<input type="text" class="form-control" id="pNo" name="pNo" data-validetta="required,minLength[10],maxLength[10]" lang="fa" style="text-align: left;">
</div>
<div class="form-group login-width-100">
<label for="mNumber" class="m-rtl-label"><span class="requiredMark"></span> telephone :</label>
<input type="text" class="form-control" id="tNumber" name="tNumber" data-validetta="required,minLength[11],maxLength[11]" lang="fa" style="text-align: left;">
</div>
<div class="form-group" style="float:right;padding-right: 20px;">
<div class="g-recaptcha" data-sitekey="...."></div>
</div>
<div class="form-group login-width-100">
<button type="submit" class="btn btn-primary colorGreenBTN">login</button>
</div>
</form>
</div>
JS:
var v = grecaptcha.getResponse();
if (v.length == 0) {
alert("fill the form");
return;
} else if (!$("#Terms").prop("checked")) {
alert("check the rules");
}
Simplest Way to validate as much g-captcha validate
Hope you have included api.js before </head> tag as per below
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit"></script>
Your HTML Code looks like below
<div class="g-recaptcha-contact" data-sitekey="Your Site Key" id="RecaptchaField2"></div>
<input type="hidden" class="hiddenRecaptcha" name="ct_hiddenRecaptcha" id="ct_hiddenRecaptcha">
<div class="g-recaptcha-quote" data-sitekey="Your Site Key" id="RecaptchaField1"></div>
<input type="hidden" class="hiddenRecaptcha" name="qt_hiddenRecaptcha" id="qt_hiddenRecaptcha">
After you add this code in footer with tag
var CaptchaCallback = function() {
var widgetId1;
var widgetId2;
widgetId1 = grecaptcha.render('RecaptchaField1', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_quote});
widgetId2 = grecaptcha.render('RecaptchaField2', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_contact});
};
var correctCaptcha_quote = function(response) {
$("#qt_hiddenRecaptcha").val(response);
};
var correctCaptcha_contact = function(response) {
$("#ct_hiddenRecaptcha").val(response);
};
And Last easy step for developer add Jquery Validation as per below
$("#form_id").validate({
ignore: [],
rules: {
ct_hiddenRecaptcha: { required: true, },
qt_hiddenRecaptcha: { required: true, },
},
});
If you have same class for both the forms, you can use it to validate above.
HeyHeyHey!
I am having this problem, for some reason it won't add the Data to my MYSQL Database and I have no idea why. I looked at a lot of other posts here on StackOverflow, but can't seem to find a post that helps me :)
Here is my code:
<script>
$('.alert-saved-changes-success2').hide();
$(".save-tradelink-profile").click(function() {
$tradelinkvalue = document.getElementById("tradelink").value;
if ($.trim($('#tradelink').val()) == '') {
alert('Tradelink can not be blank');
} else if ($tradelinkvalue.indexOf("https://steamcommunity.com/tradeoffer/new") >= 0) {
<?php //TRYING TO UPDATE DATA
$TradelinkValue = $_POST['GetTradelinkValue'];
mysql_query("UPDATE item-jackpot-users SET tradelink=$TradelinkValue WHERE steam_id=$steamid") or die(mysql_error());
?>
$("#alert-saved-changes-success").slideDown("slow");
} else {
alert('Tradelink has to be valid');
}
});
$(".logout-button-profile").click(function(){
window.location.href = "steamauth/logout.php";
});
</script>
It seems like the php tag gets loaded before everything else, since the
$('.alert-saved-changes-success2').hide();
doesn't load. It finds the error, and then just killing everything else.
Respecting the fact that yes, php is performed before your webbrowser receives the js text, you could use a form, that sends your update information into post(like using a form tag), reload the page, and make the page perform the update with your post data. You could also use ajax.
<form name="login" class="form-horizontal" method="post" action="refer to this file" >
<div class="form-group">
<label class="col-sm-3 control-label">
Username
</label>
<div class="col-sm-2">
<input class="pull-right" type="text" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">
Password
</label>
<div class="col-sm-2">
<input class="pull-right" type="password" name="password" />
</div>
</div>
<div class="form-group">
<div class=" col-sm-offset-3 col-sm-2">
<button type="submit" name="submitbtn" class="btn btn-default pull-right">
Sign in
</button>
</div>
</div>
</form>
<?php
$user = $_POST['username'];
$pwd = $_POST['password'];
//DO SOME SANITIZATION!
//Store $user and $pwd
?>
Ofcourse you could include the php part somewhere else in the file, like inside of a script tag.
I'd like to learn how to password protect my sites, with custom login credentials that I chose.
Using custom html, css, and javascript to create the interface gets me to a point like this -> http://codepen.io/lexeckhart/pen/RPLPwX
But everything on that page is accessible to everyone. I risk being an idiot in saying I remember using php and mysql or sql to do the next part. Maybe.
To add onto the title question I would like to know is where I start creating this database? Can I do it with ftp?
HTML
<div id="successful_login" class="fix-middle">
<div class="container text-center">
<h1>Welcome back to the internet!</h1>
<p>You've successfully managed to log into a nonexistant account in order to test a login dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="successful_registration" class="fix-middle">
<div class="container text-center">
<h1>Welcome to the internet!</h1>
<p>You've successfully managed to register for a nonexistant account in order to test a registration dialog box.<br> If you like it, you are welcomed to use it wherever you want, no strings attached.<br><br>Rerun the whole thing.</p>
</div>
</div>
<div id="dialog" class="dialog dialog-effect-in">
<div class="dialog-front">
<div class="dialog-content">
<form id="login_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Log in</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username" autofocus/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="text-center pad-top-20">
<p>Have you forgotten your<br><strong>username</strong> or <strong>password</strong>?</p>
</div>
<div class="pad-top-20 pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue">
</div>
<div class="text-center">
<p>Do you wish to register<br> for <strong>a new account</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
<div class="dialog-back">
<div class="dialog-content">
<form id="register_form" class="dialog-form" action="" method="POST">
<fieldset>
<legend>Register</legend>
<div class="form-group">
<label for="user_username" class="control-label">Username:</label>
<input type="text" id="user_username" class="form-control" name="user_username"/>
</div>
<div class="form-group">
<label for="user_password" class="control-label">Password:</label>
<input type="password" id="user_password" class="form-control" name="user_password"/>
</div>
<div class="form-group">
<label for="user_cnf_password" class="control-label">Confirm password:</label>
<input type="password" id="user_cnf_password" class="form-control" name="user_cnf_password"/>
</div>
<div class="form-group pad-top-20 form-group-checkbox">
<div class="checkbox">
<label>
<input type="checkbox" id="user_terms" name="user_terms">
I have read and I agree with the Terms and Conditions
</label>
</div>
</div>
<div class="pad-btm-20">
<input type="submit" class="btn btn-default btn-block btn-lg" value="Continue"/>
</div>
<div class="text-center">
<p>Return to <strong>log in page</strong>?</p>
</div>
</fieldset>
</form>
</div>
</div>
</div>
JAVASCRIPT
// The "getFormData()" function retrieves the names and values of each input field in the form;
function getFormData(form) {
var data = {};
$(form).find('input, select').each(function() {
if (this.tagName.toLowerCase() == 'input') {
if (this.type.toLowerCase() == 'checkbox') {
data[this.name] = this.checked;
} else if (this.type.toLowerCase() != 'submit') {
data[this.name] = this.value;
}
} else {
data[this.name] = this.value;
}
});
return data;
}
// The "addFormError()" function, when called, adds the "error" class to the form-group that wraps around the "formRow" attribute;
function addFormError(formRow, errorMsg) {
var errorMSG = '<span class="error-msg">' + errorMsg + '</span>';
$(formRow).parents('.form-group').addClass('has-error');
$(formRow).parents('.form-group').append(errorMSG);
$('#dialog').removeClass('dialog-effect-in');
$('#dialog').addClass('shakeit');
setTimeout(function() {
$('#dialog').removeClass('shakeit');
}, 300);
}
// FORM HANDLER:
// form_name - This attribute ties the form-handler function to the form you want to submit through ajax. Requires an ID (ex: #myfamousid)
// custom_validation -
function form_handler(form_name, custom_validation, success_message, error_message, success_function, error_function) {
$(form_name).find('input[type="submit"]').on('click', function(e) { // if submit button is clicked
window.onbeforeunload = null; // cancels the alert message for unsaved changes (if such function exists)
$(form_name).find('.form-group .error-msg').remove();
var submitButton = this;
submitButton.disabled = true; // Disables the submit buttton until the rows pass validation or we get a response from the server.
var form = $(form_name)[0];
// The custom validation function must return true or false.
if (custom_validation != null) {
if (!custom_validation(form, getFormData(form))) {
submitButton.disabled = false;
return false;
}
}
e.preventDefault(); //STOP default action
});
$(document).click(function(e) { // Whenever the user clicks inside the form, the error messages will be removed.
if ($(e.target).closest(form_name).length) {
$(form_name).find('.form-group').removeClass('has-error');
setTimeout(function() {
$(form_name).find('.form-group .error-msg').remove();
}, 300);
} else {
return
}
});
}
// LOGIN FORM: Validation function
function validate_login_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_login').addClass('active');
//return true;
}
// REGISTRATION FORM: Validation function
function validate_registration_form(form, data) {
if (data.user_username == "") {
// if username variable is empty
addFormError(form["user_username"], 'The username is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_password == "") {
// if password variable is empty
addFormError(form["user_password"], 'The password is invalid');
return false; // stop the script if validation is triggered
}
if (data.user_cnf_password == "" || data.user_password != data.user_cnf_password) {
// if password variable is empty
addFormError(form["user_cnf_password"], "The passwords don't match");
return false; // stop the script if validation is triggered
}
if (!data.user_terms) {
// if password variable is empty
addFormError(form["user_terms"], "You need to read and accept the Terms and Conditions before proceeding");
return false; // stop the script if validation is triggered
}
$('#dialog').removeClass('dialog-effect-in').removeClass('shakeit');
$('#dialog').addClass('dialog-effect-out');
$('#successful_registration').addClass('active');
//return true;
}
form_handler("#login_form", validate_login_form, null, null, null, null, null, null);
form_handler("#register_form", validate_registration_form, null, null, null, null, null, null);
var dialogBox = $('#dialog');
dialogBox.on('click', 'a.user-actions', function() {
dialogBox.toggleClass('flip');
});
$('#successful_login,#successful_registration').on('click', 'a.dialog-reset', function() {
$('#successful_login,#successful_registration').removeClass('active');
dialogBox.removeClass('dialog-effect-out').addClass('dialog-effect-in');
document.getElementById('login_form').reset();
document.getElementById('register_form').reset();
});
Store the credentials in MySQL in a database table (hashed), access the database via php, redirect the user using either php or javascript.
Can I have yout help pleas there,I make a validation field for a popup form :
function prepareEventHandlers() {
document.getElementById("contact").onsubmit = function () {
if (document.getElementById("message").value == '') {
document.getElementById("errorMessage").innerHTML = 'the field should not be empty!';
return false;
}
else {
document.getElementById("errorMessage").innerHTML = '';
return true;
}
};
}
window.onload = function () {
prepareEventHandlers();
}
then the html code :
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-body">
<form class="contact" name="contact" >
<label class="label" for="message">Enter a Message</label><br>
<textarea id="message" name="message" class="input-xlarge"></textarea>
<p><span id="errorMessage"></span></p>
</form>
</div>
<div class="modal-footer">
<input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
No!
</div>
and I got this error :
TypeError: document.getElementById(...) is null document.getElementById("contact").onsubmit = function () {
Any Idea?
Edit:
OK I add id="contact" to my form so the error is gone but now the popup form is displyaed but when I try to click send with empty or not empty value nothing is happened...
just close </form> after <input class="btn btn-success" type="submit" value="Send!" id="btnsubmit">
and change html form id to contact