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.
Related
I have form which contain email input field
<form id="TypeValidation" action="" method="post" enctype='multipart/form-data'>
<div class="form-group has-label col-sm-6">
<label>
Email
</label>
<input class="form-control" name=email" type="email" required>
</div>
<div class="card-footer text-center">
<button type="submit" name="add_usr_acc" id="add_usr_acc" value="add_usr_acc" class="btn btn-primary" >Add</button>
</div>
</div>
</form>
Issue is that in script code when alert on email then come undefined. how to get value in which user type a email
<script>
$("#TypeValidation").on('submit', (function(e) {
var email = $(this).find('input[name="email"]').val();
alert(email); {
e.preventDefault();
$.ajax({
url: "fn_acc_submit.php?addUsraccID=" + addUsraccID,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "html",
beforeSend: function() {
$("#add_usr_acc").prop('disabled', 'disabled')
},
success: function(result) {
alert(result);
location.reload();
if (result == '1') {
location.replace("lst_user_account.php");
} else {
location.replace("add_user_account.php");
}
}
});
}
}));
</script>
Please fix my problem where I am doing wrong.
Problem is in your HTML code at below line:
<input class="form-control" name=email" type="email" required>
Here name=email" is not valid.
Change this to name="email"
In you input field, it should name="email". You forgot to add opening quotes.
I'm very confuse for this problem ajax post data, on localhost working but on shared hosting not working. This is my code
<script type="text/javascript">
$(document).ready(function(){
$("#login").click(function(){
alert('asdf');
var page = "login";
var username = $("#username").val().trim();
var password = $("#password").val().trim();
$.ajax({
url:'pages/content/input_query.php',
type:'post',
data:{page:page,username:username,password:password},
success:function(response){
var msg = "";
if(response ==1){
window.location = "index.php?pages=home";
}else{
$("#result").html(response);
}
}
});
});
});
and my code html is
<form role="form" action="pages/content/input_query.php" method="post">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="username" id="username" />
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="password" />
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
</div>
</div><!-- /.col -->
<div class="col-xs-4">
<button type="button" class="btn btn-primary btn-block btn-flat" id="login">Sign In</button>
</div><!-- /.col -->
</div>
</form>
And I have add code alert('asdf') , but there are no alert message every click the button. What is the problem. Please help me. Every answer I appricated
Have you called jQuery on server?
Try calling from jQuery CDN.
Use this code:
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login").click(function(){
alert('asdf');
var page = "login";
var username = $("#username").val().trim();
var password = $("#password").val().trim();
$.ajax({
url:'pages/content/input_query.php',
type:'post',
data:{page:page,username:username,password:password},
success:function(response){
var msg = "";
if(response ==1){
window.location = "index.php?pages=home";
}else{
$("#result").html(response);
}
}
});
});
});
</script>
Try preventing the default action of the #login element and when you pass the POST type, you must use uppercases. Something like:
<script type="text/javascript">
$(document).ready(function(){
$("#login").click(function(event){
event.preventDefault();
alert('asdf');
var page = "login";
var username = $("#username").val().trim();
var password = $("#password").val().trim();
$.ajax({
url:'pages/content/input_query.php',
type:'POST',
data:{page:page,username:username,password:password},
success:function(response){
var msg = "";
if(response ==1){
window.location = "index.php?pages=home";
}else{
$("#result").html(response);
}
}
});
});
});
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;
}
}
I'm pretty new in web development and I know this might sound like a very simple question but I'm trying to add a login functionality in a bootstrap template.
The .js with the template validates the contents of the text and such. I'm trying to add a POST function in the submitHandler.
$(document).ready(function() {
$('#login-form').validate({
focusInvalid: false,
ignore: "",
rules: {
txtusername: {
minlength: 2,
required: true
},
txtpassword: {
required: true,
}
},
invalidHandler: function (event, validator) {
//display error alert on form submit
},
errorPlacement: function (label, element) { // render error placement for each input type
$('<span class="error"></span>').insertAfter(element).append(label)
var parent = $(element).parent('.input-with-icon');
parent.removeClass('success-control').addClass('error-control');
},
highlight: function (element) { // hightlight error inputs
},
unhighlight: function (element) { // revert the change done by hightlight
},
success: function (label, element) {
var parent = $(element).parent('.input-with-icon');
parent.removeClass('error-control').addClass('success-control');
},
submitHandler: function(form) {
var username=$("#txtusername").val();
var password=$("#txtpassword").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
success: function(data){
if(data) {
window.location.href = "index.php";
} else {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
});
});
<?php
if (isset($_POST['submit'])) { // Form has been submitted.
$username = ($_POST['username']));
$password = ($_POST['password']));
.
.
.
.
.
}
else
{
echo "Doesnt Work";
}
?>
.
.
.
<form id="login-form" class="login-form" action="#" method="post">
<div class="row">
<div class="form-group col-md-10">
<div id="error"></div>
<label class="form-label">Username</label>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="text" name="txtusername" id="txtusername" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-10">
<label class="form-label">Password</label>
<span class="help"></span>
<div class="controls">
<div class="input-with-icon right">
<i class=""></i>
<input type="password" name="txtpassword" id="txtpassword" class="form-control">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-10">
<button class="btn btn-primary btn-cons pull-right" type="submit">Login</button>
</div>
</div>
</form>
Thanks in advance!
Please check the documention of data sent to the server. You can use object to send your data. In the link above, there are some examples how to send data to server.
var dataString = {username: username, password: password}
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.