1

My form is like this

<form data-mage-init='{"validation":{}}' id="donation-request-form" method="post" data-hasrequired="* Required Fields">
 <div class="row">
 <div class="col-lg-6 col-md-6 col-xs-12 row-padding">
 <span class="fname-icon"></span>
 <input type="text" class="form-control fname" id="first_name" name="first_name" placeholder="First Name" data-validate='{"required":true}'>
 </div>
 <div class="col-lg-6 col-md-6 col-xs-12 row-padding">
 <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name">
 </div>
 </div>
 <div class="form-button button-section">
 <input class="btn-orange" type="submit" value="Request Donation" onclick="SendForm()">
 </div>
</form>

This is my SendForm() function

<script type="text/javascript">
function SendForm() { 
 var customurl = "<?php echo $baseURL_l.'emails/index/index'?>";
 alert(customurl);
 jQuery.ajax({
 type : 'POST',
 url : customurl,
 data : jQuery('#donation-request-form').serialize(),
 success: function(msg){
 alert(msg);
 }
 });
}

If i click submit button without filling any values of the form it will redirect to the controller and after the form validation is happening.

I want to validate first and submit the form to controller second. I do not want to do any custom js validation.I want to use only magento validation.

asked Dec 29, 2017 at 5:35
1

2 Answers 2

9

Try this:

if (jQuery('#donation-request-form').valid()) {
 jQuery.ajax({
 type : 'POST',
 url : customurl,
 data : jQuery('#donation-request-form').serialize(),
 success: function(msg){
 alert(msg);
 }
 });
}
answered Dec 29, 2017 at 6:11
0
5

I found a good way of form submission with AJAX while using magento2 default form validation which I would like to share with the community.

We simply use below code for form validation

require([‘jquery’,’mage/validation’], function($){
 var dataForm = $(‘#form-validate’);
 dataForm.mage(‘validation’, {});
});

We can extend this to :

require([‘jquery’,’mage/validation’], function($) {
 var dataForm = $(‘#form-validate’);
 dataForm.mage(‘validation’, {});
 $(‘button#submit-button’).click( function() { //can be replaced with any event 
 var status = dataForm.validation(‘isValid’); //validates form and returns boolean
 if(status) {
 console.log(‘form is validated’); //form is valid
 //Do the AJAX call here
 } else {
 console.log(‘form is not validated’); 
 } 
 });
});

You can find detail description in this link.

Hope this helps!!

answered Jan 29, 2018 at 9:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.