Materializecss with jquery validation not working - javascript

HTML markup;
<div id="address" class="col s12">
<div class="row">
<form method="post" action="" id="addressDetails">
<div class="input-field col s6">
<textarea id="lAddress" name = 'lAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea>
<label for="lAddress" data-error="Must be between 20 to 100 Characters">Local Address</label>
</div>
<div class="input-field col s6">
<textarea id="pAddress" name = 'pAddress' minlength='20' maxlength='100' class="materialize-textarea" class="validate" required length="100"></textarea>
<label for="pAddress" data-error="Must be between 20 to 100 Characters">Permanent Address</label>
</div>
</form>
</div>
<div class="row center-align">
<button type="submit" name="submitAddress" form="addressDetails" class="waves-effect waves-light light-blue darken-1 btn updateProfile">Save Address Details</button>
</div>
</div>
JavaScript code:
function updateProfile(event) {
console.log(this);
event.preventDefault();
form = $(this).closest('.col.s12').find('form');
$.ajax('profile/updateProfile.php', {
type: "POST",
dataType: "json",
data: form.serialize(),
success: function(result) {
Materialize.toast(result.message, 4000);
},
error: function() {
Materialize.toast("Failed: Please contact admin.", 4000);
},
timeout: 5000
});
}
$(document).ready(function() {
$("button.updateProfile").on('click', updateProfile);
});
Earlier with normal form submission validation was working. But now with jQuery AJAX request I am able to send data, but when form is invalid then it shows error in red but it accepts the form with error.
When I am using $("button.updateProfile").on('sumbit', updateProfile); it is validating but it is reloading the page and preventDefault is not working.

$("button.updateProfile").on('click', updateProfile);
This will not validate with the help of materialize validate. You have to look for submit.
Again with submit it will have problem, it is not looking for submission in form.
$("button.updateProfile").on('sumbit', updateProfile);
Instead of button use form, then will look for form submission. Like this
$("form").on('submit', updateProfile);
This will work perfectly.
So remember whenever you are submitting a form check for submit on form not on submit buttons.

Related

Form get submitted even the form validation fails

I am using http://www.formvalidator.net/index.html to validate my form but the form gets submitted even when the validation get failed.
Form code:
<form name="add-todo" class="form-horizontal" action="" method="post">
<h5>Add New Item</h5>
<div class="form-group">
<div class="col-md-12">
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<button type="submit" class="btn btn-primary btn-add">Add</button>
</div>
</div>
</form>
jQuery code:
$(document).ready(function() {
$.validate({
modules: 'security'
});
$('form[name=add-todo]').submit(function(e) {
e.preventDefault();
var text = $("#todo-text-input").val();
$('.btn-add').text('Saving ....');
$.ajax({
url: this.action,
type: this.method,
data: {
text: text
},
success: function(response) {
$("#todo-text-input").empty();
$('.messages').removeClass('hide-element');
$('.alert').addClass('alert-success');
$('.alert').text('To do item added successfully.');
$('.alert').fadeTo(2000, 500).slideUp(500, function() {
$('.alert').slideUp(500);
});
}
});
});
});
dont use submit button. You can use
<button type="button" class="btn btn-primary btn-add">Add</button>
after that check your validation status. if its valid then submit the form.
<input type="text" data-validation="required" class="form-control" id="todo-text-input" name="todo-text">
In your input field you don't need to use data-validation="required" just use required like
<input type="text" required class="form-control" id="todo-text-input" name="todo-text">
Please change you form validation code configuration like this:
$.validate({
form : '#registration-form',
modules : 'security',
onSuccess : function($form) {
alert('The form '+$form.attr('id')+' is valid!');
// write your ajax code to submit form data on server
return false; // Will stop the submission of the form
}
});
For more info follow:
http://www.formvalidator.net/index.html#configuration

button type submit refreshes page instead of triggering ajax network request [duplicate]

Alright, I have a simple form comprising of only a text field. Data written in the text field is stored in DB when we hit submit (Stored via ajax). The ajax works fine and data is submitted, however, the page get's refreshed automatically and the URL contains the content of the input field.
My Form :-
<form class="form-horizontal">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="message"></label>
<div class="col-md-5">
<input id="message" name="message" type="text" placeholder="message" class="form-control input-md" required="">
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit_message"></label>
<div class="col-md-4">
<button id="submit_message" name="submit_message" class="btn btn-success">Enter</button>
</div>
</div>
</fieldset>
</form>
Ajax :-
$("#submit_message").click(function() {
var message = $("#message").val();
$.ajax({
type: "POST",
url: "ajax_getter.php?requestid=2",
data: { message: message, c: c },
dataType: "html"
}).done(function( msg ) {
//load_content();
alert(msg);
});
});
PHP :-
//...
if($chat->insert("chat_threads", $arr))
{
echo 1;
}
else
{
echo 0;
}
After the result is show in the popup, the page refresh and the URL becomes something like :- chat.php?message=454545&submit_message=
Why is the page being refreshed ?
Seems that your form is being submitted. Try preventing the default event (i.e. submission):
$("#submit_message").click(function(e) {
e.preventDefault(); // This prevents form from being sumbitted
// the rest of your code
});

Why is my email validation not working in bootstrap and html5?

I have the following form on my page:
<div class="form-group">
<form class="form-horizontal general subscribe" name="commentform" id="subscribe" method="post" action="#">
<div class="col-lg-8 col-md-8 col-xs-8 lower">
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" />
</div>
<div class="col-lg-4 col-md-4 col-xs-4">
<input type="submit" class="btn btn-fill btn-info form_submit" value="Subscribe"/>
</div>
<div id="form_results"></div>
</form>
</div>
and my jquery code for handling the email stuff is as follows:
jQuery(document).ready(function($) {
"use strict";
$('.form_submit').click(function() {
var form = $(this).parents('form');
$.ajax({
url: 'http://mywebservice/mail',
type: "POST",
data: {
email: $('input[name=subscribe_email]').val()
},
dataType:'json',
success: function(response) {
output = '<p>Thanks, we will contact you soon!</p>';
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}
});
return false;
});
});
and now the email is added successfuly to the database each time user presses the Subscribe button, but the problem is that the email is not validated with an official email pattern. I thought that in html5 the only necessary check is this <input type="email" but it does not work properly... How can I prevent users from adding wrong email addresses to the database?
You need to add required attribute for a field to be validated
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" required="required" />
If you submit the form using normal submit button then required fields are validated automatically.
If you are submitting or calling javasript function on submit button then
you can use form.checkValidity() to validate the required controls.
jQuery(document).ready(function($) {
"use strict";
$('.form_submit').click(function(){
var form = $(this).parents('form');
form.checkValidity()
$.ajax({
url: 'http://mywebservice/mail',
type: "POST",
data: {
email: $('input[name=subscribe_email]').val()
},
dataType:'json',
success: function(response)
{
output = '<p>Thanks, we will contact you soon!</p>';
$("#contacts_form .form_item").val('');
form.find('.form_inner').slideUp();
form.find("#form_results").hide().html(output).slideDown();
}
});
return false;
});
});
add required attribute for <input type="email" and sure there is no JavaScript error on the page as well.
You need to add required attribute as per HTML input with type email requires that before it can perform any validation.
<input type="email" placeholder="Enter your email" class="email requiredField form-control" name="subscribe_email" required />
You can also look into https://jqueryvalidation.org/, I use it and its awesome it allows you show custom message to users

How to validate coupon using Stripe's JavaScript API?

I am using Stripe's API (v2) - https://stripe.com/docs/stripe.js
This is being implemented using Laravel's cashier, a package that ships with Laravel, with docs.
I have a very basic form at the moment, collecting the user's card info, which is then passed over to Stripe who will validate it and return a token. This token is placed in my form and is what I store and use in my system (again, all handled cleanly by Laravel).
I need to use coupons as part of this checkout process. I assumed it would be a simple case of adding the coupon field and Stripe would do the rest, but unfortunately that isn't the case - there is no validation taking place of the coupon when it is entered and the form is submitted.
Processing the coupon after submit is fine, as Laravel handles that.
My question: How can I get Stripe to validate an entered coupon using their JavaScript API?
Below is my form and the accompanying JS:
Form:
<form method="POST" action="/subscribe/individual" accept-charset="UTF-8" class="form-horizontal" role="form" id="subscription-form">
<input name="_token" type="hidden" value="ep1tcaWMRGrPOLSkBCBJQo1USynWW6aTjDh9xN3W">
<div class="payment-errors"></div>
<div id="signupalert" style="display:none" class="alert alert-danger">
<p>Error:</p>
<span></span>
</div>
<div class="form-group">
<label for="ccn" class="col-md-3 control-label">Credit card number</label>
<div class="col-md-9">
<input class="form-control" data-stripe="number" name="ccn" type="text" value="" id="ccn">
</div>
</div>
<div class="form-group">
<label for="expiration" class="col-md-3 control-label">Expiration date</label>
<div class="col-md-6">
<select class="form-control" data-stripe="exp-month" name="month"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select>
</div>
<div class="col-md-3">
<select class="form-control" data-stripe="exp-year" name="year"><option value="2014" selected="selected">2014</option><option value="2015">2015</option><option value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option><option value="2019">2019</option><option value="2020">2020</option><option value="2021">2021</option><option value="2022">2022</option><option value="2023">2023</option><option value="2024">2024</option><option value="2025">2025</option><option value="2026">2026</option><option value="2027">2027</option><option value="2028">2028</option><option value="2029">2029</option></select>
</div>
</div>
<div class="form-group">
<label for="cvc" class="col-md-3 control-label">CVC number</label>
<div class="col-md-3">
<input class="form-control" data-stripe="cvc" name="cvc" type="text" value="" id="cvc">
</div>
</div>
<div class="form-group">
<label for="coupon" class="col-md-3 control-label">Coupon</label>
<div class="col-md-3">
<input class="form-control" data-stripe="coupon" name="coupon" type="text" value="" id="coupon">
</div>
</div>
<div class="form-group">
<!-- Button -->
<div class="col-md-offset-3 col-md-9">
<button type="submit" id="btn-signup" class="btn btn-info">Sign Up</button>
</div>
</div>
JavaScript:
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script>
Stripe.setPublishableKey('*** removed ***');
jQuery(function($) {
$('#subscription-form').submit(function(event) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
var stripeResponseHandler = function(status, response) {
var $form = $('#subscription-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
</script>
I'm pretty sure you can't.
I'm validating the coupon via ajax, and make a server side call to Stripe. You can then apply the coupon to any purchase transactions on the server side when you accept the POST.
The solution I found is to
create a coupon on the Stripe dashboard
use the same value for the coupon id and code
Then by calling the coupons retrieve method you get a boolean attribute "valid" in the coupon response returned.
Here's a response example from Stripe Docs:
{
"id": "25_5OFF",
"object": "coupon",
"amount_off": null,
"created": 1617028691,
"currency": "usd",
"duration": "repeating",
"duration_in_months": 3,
"livemode": false,
"max_redemptions": null,
"metadata": {},
"name": "25.5% off",
"percent_off": 25.5,
"redeem_by": null,
"times_redeemed": 0,
"valid": true
}

Single click event acts as double click event

I'm using Ajax to submit the login form without refreshing the page. I've added a function to see whether the data returns 'error' (which comes up when the user enters an incorrect email/password). If it does not return 'error', the user has been logged in and will be transferred to the page within 2 seconds.
The problem is that my button acts like a double-click button and I cannot see why. This is my JS file:
$(function() {
$("#goLogin").click(function() {
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
});
function finishLogin( data , textStatus ,jqXHR ) {
if ( data == "error" ) {
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
} else {
$('.succesMsg').fadeIn(500).show();
$('.errorMsg').fadeOut(300).hide();
setTimeout("location.href = 'protected.php';",2000);
}
}
I've tried placing it between the document_ready tags, but that isn't working either.
Part of the HTML code:
<div class="login form">
<div class="login-header">Please Login</div>
<form method="post" id="loginForm" name="form">
<label for="email" class="short">Email*</label>
<input type="text" name="email" id="email" class="required" placeholder="" />
<label for="password" class="short">Password *</label>
<input type="password" name="password" id="password" class="required" placeholder="" maxlength="15" />
</form>
<div id="login-functions">
<div class="loginbtn-container">
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Login" />
</div>
<div class="login form actions">
<p class="register account">Register an account</p>
<p class="request password">Lost your password?</p>
</div>
</div>
</div>
<div class="errorMsg">Incorrect. Please recheck your details</div>
<div class="succesMsg"><b>You've been logged in!</b> Please wait while we transfer you</div>
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
did you mean tto hide both? I see the click is working fine, though you should ideally do submit
Take your submit inside the form, and prevent normal form submit using preventDefault()
$("#goLogin").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
Please move your submit button inside the form closing tag first
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Inloggen" />
The above button is placed after the </form> tag.
Because you click on input type submit and progress Ajax on it; it cause submit 2 times.
To avoid it, you can use as Zach Leighton said above ; or use as below
$("#goLogin").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});

Categories