Show javascript variable in html div - javascript

Once a form is submitted my javascript hides one div and shows another:
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
The bottom line is where I'm trying to add some text to the div that is dynamically displayed. However, nothing is displayed in the div. I'd also like to show the variable from another function in the same file.
it's the var e = $("#username").val(); from the code below which I would like to add to the div eventually.
function init() {
document.addEventListener("deviceready", deviceReady, true);
delete init;
}
function checkPreAuth() {
console.log("checkPreAuth");
var form = $("#loginForm");
if(window.localStorage["username"] != undefined && window.localStorage["password"] != undefined) {
$("#username", form).val(window.localStorage["username"]);
$("#password", form).val(window.localStorage["password"]);
handleLogin();
}
}
function handleLogin() {
var e = $("#username").val();
var p = $("#password").val();
if(e != "" && p != "") {
$.ajax({
type: 'POST',
url: 'http://localhost/php/log.php',
crossDomain: true,
data: {username: e, password :p},
dataType: 'json',
async: false,
success: function (response){
if (response.success) {
$.mobile.changePage("#loginTest");
}
else {
alert("Your login failed");
}
},
error: function(error){
alert('Could not connect to the database' + error);
}
});
}
else {
alert("You must enter username and password");
}
return false;
}
function deviceReady() {
console.log("deviceReady");
$("#loginPage").on("pageinit",function() {
console.log("pageinit run");
$("#loginForm").on("submit",handleLogin);
checkPreAuth();
});
$.mobile.changePage("#loginTest");
$('#loginTest').html('Hello World!');
}
HTML Code:
<body>
<div id="loginPage" data-role="page">
<div data-role="header">
<h1>Auth Demo</h1>
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="Username" />
</div>
<div data-role="fieldcontain" class="ui-hide-label">
<label for="password">Password:</label>
<input type="password" name="password" id="password" value="" placeholder="Password" />
</div>
<input type="button" value="Login" id="submitButton" onclick="handleLogin()">
<div data-role="footer">
</div>
</div>
<div id="loginTest" data-role="page">
<div id="name">
</div>
</div>
</body>

try this on element id loginTest (#loginTest)
document.getElementById('loginTest').innerHTML= your variable here; //or any string
if you are using jquery
$( '#loginTest' ).text( your variable ); //or any string

Wouldn't you be better to restrict the post back:
<input type="button" value="Login" id="submitButton" onClientClick="handleLogin()">
and then return false from the function.

Related

Return false not working after form submit

I'm submiting a contact form to my backend script with bootstrap form and ajax.
return false is not preventing my form from submiting again after ajax callback. This causes a new bootstrap form validation, displaying input errors messages.
I read some similar questions even with event.preventDefault() but it did not work.
html
<body>
<form id="contact-form" method="POST" class="needs-validation" onsubmit="return false" novalidate>
<div class="form-group">
<label for="name">Nome</label>
<input type="text" name="name" id="name" class="form-control" required />
<div class="invalid-feedback">
Please, type your name
</div>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" required />
<div class="invalid-feedback">
Please, type your e-mail
</div>
</div>
<div class="form-group">
<label for="subject">Assunto</label>
<input type="text" name="subject" id="subject" class="form-control" />
</div>
<div class="form-group">
<label for="message">Mensagem</label>
<textarea name="message" id="message" class="form-control" rows="3" required minlength="10"></textarea>
<div class="invalid-feedback">
Leave your message
</div>
</div>
<button type="submit" class="btn send-btn">Enviar</button>
<div id="messages" class="show_messages"></div>
<div id="error_messages" class="show_error"></div>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script>
(function () {
'use strict';
window.addEventListener('load', function () {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if (form.checkValidity() === true) {
var name = $("input#name").val();
var email = $("input#email").val();
var subject = $("input#subject").val();
var message = $("textarea#message").val();
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
var url = "./serverside/send-mail.php";
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function (data) {
console.log(data);
var response = JSON.stringify(data);
console.log(response);
if (data == "\"E-mail sent\"") {
console.log("email sent after stringify");
$("#messages").addClass("messages")
.html("<img src='./img/check.png' alt='Check' /> Message sent!")
.hide().fadeIn(800, function () {
setTimeout(() => {
$("#messages").hide(500);
}, 3000);
});
$('#contact-form')[0].reset();
} else {
$('#contact-form')[0].reset();
console.log("E-mail was not sent");
$("#error_messages").addClass("error_messages")
.html("<img src='./img/warning.png' alt='Warning' /> Ops! Error sending your message.")
.hide().fadeIn(800, function () {
setTimeout(() => {
$("#error_messages").hide(500);
}, 3000);
});
}
},
error: function (e) {
console.log(e);
$("#error_messages").addClass("error_messages")
.html("<img src='./img/warning.png' alt='Warning' /> Ops! Error sending your message.")
.hide().fadeIn(800, function () {
setTimeout(() => {
$("#error_messages").hide(500);
}, 3000);
});
}
});
return false;
}
}, false);
});
}, false);
})();
</script>
</body>
After some tests I finally found the solution. After reset() the form I should remove the class was-validated.
if (data == "\"E-mail sent\"") {
console.log("email sent after stringify");
$("#messages").addClass("messages")
.html("<img src='./img/check.png' alt='Check' /> Message sent!")
.hide().fadeIn(800, function () {
setTimeout(() => {
$("#messages").hide(500);
}, 3000);
});
$('#contact-form')[0].reset();
form.classList.remove('was-validated');
} else {
...
Maybe it is a workaround but it worked.

Ajax form submit without page refresh

I simply want to submit my form to the same page with ajax without page refresh. So my below code submits the form but $_POST values are not picked ... Am I submitting it properly. I don't get any error but I think my form is not submitting.
html form
<form action="" id="fixeddonation" name="fixeddonation" method="post">
<input type="hidden" class="donerProject" name="donerProject" value="test">
<input type="hidden" class="donersubProject" id="donersubProject" name="donersubProject" value="general">
<input type="hidden" class="donerLocations" id="donerLocations" name="donerLocations" value="general">
<input type="hidden" class="donationpagetype" name="donationpagetype" value="general">
<input type="hidden" class="projectadded" id="projectadded" name="projectadded" value="1">
<input type="hidden" value="302" id="pageid" name="pageid">
<div class="classsetrepet generalfixshow fullrow row fixed-page">
<div class="col-6 text-right">
<div class="prize">Fixed Amount £</div>
</div>
<div class="col-6">
<input type="text" id="oneoffamt" name="oneoffamt" class="oneoffamt validatenumber">
<span class="amt_error"></span>
</div>
</div>
<br>
<div class="row">
<div class="col-6"></div>
<div class="col-6">
<input type="submit" id="submit_gen_one" class="btn-block" value="submit" name="submit_gen_one">
</div>
</div>
</form>
Ajax code
jQuery('#fixeddonation').on('submit', function (e) {
e.preventDefault();
jQuery.ajax({
type: 'post',
url: 'wp-admin/admin-ajax.php',
data: jQuery('#fixeddonation').serialize(),
success: function (data) {
alert(data);
alert('form was submitted');
jQuery('#collapse2').addClass('in').removeAttr('aria-expanded').removeAttr('style'); jQuery('#collapse1').removeClass('in').removeAttr('aria-expanded').removeAttr('style');
}
});
return false;
});
Add a correct value to the action tag of your form and try this:
<script>
$(document).ready(function() {
var form = $('#fixeddonation');
form.submit(function(ev) {
ev.preventDefault();
var formData = form.serialize();
$.ajax({
method: 'POST',
url: form.attr('action'),
data: formData
}) .done(function(data) {
alert(data);
});
});
}); // end .ready()
</script>
Don't need return false as you already called preventDefault() first thing
First create Template
<?php
/* Template Name: Test */
get_header();
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<p class="register-message" style="display:none"></p>
<form action="#" method="POST" name="testregister" class="register-form">
<fieldset>
<label><i class="fa fa-file-text-o"></i> Register Form</label>
<input type="text" name="firstname" placeholder="Username" id="firstname">
<p id="firstname-error" style="display:none">Firstname Must Be Enter</p>
<input type="email" name="email" placeholder="Email address" id="email">
<p id="email-error" style="display:none">Email Must Be Enter</p>
<input type="submit" class="button" id="test" value="Register" >
</fieldset>
</form>
<script type="text/javascript">
jQuery('#test').on('click',function(e){
e.preventDefault();
var firstname = jQuery('#firstname').val();
var email = jQuery('#email').val();
if (firstname == "") {
jQuery('#firstname-error').show();
return false;
} else {
jQuery('#firstname-error').hide();
}
if (email == "") { jQuery('#email-error').show(); return false; }
else { jQuery('#email-error').hide(); }
jQuery.ajax({
type:"POST",
url:"<?php echo admin_url('admin-ajax.php'); ?>",
data: {
action: "test",
firstname : firstname,
email : email
},
success: function(results){
console.log(results);
jQuery('.register-message').text(results).show();
},
error: function(results) {
}
});
});
</script>
</main><!-- #main -->
</div><!-- #primary -->
after that create a function (function.php in wordpress)
add_action('wp_ajax_test', 'test', 0);
add_action('wp_ajax_nopriv_test', 'test');
function test() {
$firstname = stripcslashes($_POST['firstname']);
$email = stripcslashes($_POST['email']);
global $wpdb;
$q = $wpdb->prepare("SELECT * FROM wp_test WHERE email='".$email."' ");
$res = $wpdb->get_results($q);
if(count($res)>0)
{
echo "Email Allready Register ";
}
else
{
$user_data = array(
'firstname' => $firstname,
'email' => $email
);
$tablename = $wpdb->prefix.'test'; // if use wordpress
$user_id= $wpdb->insert( $tablename,$user_data );
echo 'we have Created an account for you';
die;
}
}

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

After form validation, form doesn't submit

So my issue is this. I have some "validation" on my email and checkbox to check whether they are empty. That seemed to work, but after they have been filled in and checked I still get my warning message (.error) popup and the form does not submit.
I had this working previously with just the email, but needed to add the checkbox for an agreement.
Here is the code and a jsfiddle.
Thank you for any help!
html:
<form class="form" action="">
<div class="wrapper-input email">
<input id="email" type="text" name="email" placeholder="youremailaddress#example.com" />
<button class="form-submit submit">Sign-Up</button>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="wrapper-input">
<input type="checkbox" id="terms" name="terms" value="Agree"> <span>Click to agree</span>
</div> </form> <div class="modal">
<div class="modal-title">
<h4 class="success">Submission Successful!</h4>
<h4 class="error">Submission Error!</h4>
<img class="close" src="img/close-x.png" alt="close" />
</div>
<div class="modal-content">
<p class="success">Sucess</p>
<p class="error">Error!</p>
</div> </div>
javascript:
$(document).ready(function() {
$(".submit").click(function() {
var email = $("#email").val();
var dataString = 'email='+ email;
var terms = $("input:checkbox#terms").val();
if (!terms.checked) {
$('.lk-modal').show();
$('.success').hide();
$('.error').show();
}
if (email ==='') {
$('.lk-modal').show();
$('.success').hide();
$('.error').show();
}
else {
$.ajax({
type: "POST",
url: "collect.php",
data: dataString,
success: function(){
$('.lk-modal').show();
$('.success').show();
$('.error').hide();
}
});
}
return false;
});
});
Edit: Please look at Stefano Dalpiaz answer first as he points out your mistakes.
All you have to do to check if a string is empty is this if ( !email ) (How do you check for an empty string in JavaScript?). You can also use .is(':checked') to determine if a checkbox is checked.
Here is a working fiddle: http://jsfiddle.net/p28am/1/
HTML:
<form class="form" action="">
<div class="wrapper-input email">
<input id="email" type="text" name="email" placeholder="youremailaddress#example.com" />
<button class="form-submit submit">Sign-Up</button>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="wrapper-input">
<input type="checkbox" id="terms" name="terms" value="Agree"> <span>Click to agree</span>
</div>
</form>
<div class="modal">
<div class="modal-title">
<h4 class="success">Submission Successful!</h4>
<h4 class="error">Submission Error!</h4>
<img class="close" src="img/close-x.png" alt="close" />
</div>
<div class="modal-content">
<p class="success">Sucess</p>
<p class="error">Error!</p>
</div>
</div>
JS:
$(document).ready(function () {
$(".submit").click(function () {
var email = $("#email").val();
var dataString = 'email=' + email;
var terms = $("input:checkbox#terms").is(':checked');
if (!email || !terms) {
$('.modal').show();
$('.success').hide();
$('.error').show();
} else {
$.ajax({
type: "/echo/json/",
url: "collect.php",
data: dataString,
success: function () {
$('.modal').show();
$('.success').show();
$('.error').hide();
}
});
}
return false;
});
});
$('.close').click(function(e){
e.preventDefault();
$('.modal').hide();
});
There are a few errors on your code. For the checkbox, you are checking the .checked property of its value, and the value of a checkbox is a string. I have also added an else statement before checking for the email. Without it, the request would be sent even if you didn't check the checkbox. Here is the updated version:
$(document).ready(function () {
$(".submit").click(function () {
var email = $("#email").val();
var dataString = 'email=' + email;
var terms = $("input:checkbox#terms");
if (!terms.is(":checked")) {
$('.modal').show();
$('.success').hide();
$('.error').show();
}
else if (email === '') {
$('.modal').show();
$('.success').hide();
$('.error').show();
} else {
$.ajax({
type: "/echo/json/",
url: "collect.php",
data: dataString,
success: function () {
$('.modal').show();
$('.success').show();
$('.error').hide();
}
});
}
return false;
});
});
And here is the JsFiddle.

How to make input.error work on all fields?

http://jsfiddle.net/Nvt2h/
I am using this script which sends details from input fields to my email. As you can see, there is input.error which highlights the field in red if there is an incorrect entry. However, this currently works only for Field 1 and Field 4.
How can I make this work on field 2 and 3 as well ?
<form id="contact" name="contact" action="#" method="post">
<div class="form-group">
<label for="msg">Field1:
</label>
<input name="msg" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="id">Field2:</label>
<input name="id" type="msg" class="form-control" id="msg">
</div>
<div class="form-group">
<label for="pb">Field3:
</label>
<input name="pb" type="msg" class="form-control" id="pb">
</div>
<div class="form-group">
<label for="email">Field4:</label>
<input name="email" type="email" class="form-control" id="email">
</div>
<button id="send">Submit</button>
Add a minlength attribute to those input fields
<input name="msg" type="msg" class="form-control msg" id="msg" minlength="2">
then
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function () {
//$(".modalbox").fancybox();
$("#contact").submit(function () {
return false;
});
$("#send").on("click", function () {
$('#contact input.error').removeClass('error');
var emailval = $("#email").val();
var mailvalid = validateEmail(emailval);
if (mailvalid == false) {
$("#email").addClass("error");
}
var minlen = $('#contact input[minlength]').filter(function(){
return this.value.length < +$(this).attr('minlength')
}).addClass('error').length;
if (mailvalid == true && minlen == 0) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<p><strong>Sending, please wait...</strong></p>");
$.ajax({
type: 'POST',
url: 'send.php',
data: $("#contact").serialize(),
dataType: 'jsonp',
success: function (data) {
if (data.result == true) {
$("#contact").fadeOut("fast", function () {
$(this).before("<p class='success'><strong>Thank you, your message has been sent. We will be in touch shortly.</strong></p>");
});
} else { /* if you want to handle mail send failed, put it here */
}
},
error: function (jqXHR, textStatus, errorThrown) {
// this is triggered if there's a problem getting the jsonp back from the server
}
});
}
});
});
Demo: Fiddle

Categories

Resources