Form validation quit working after adding ajax submission to page - javascript

I had a regular form submission page the old fashion way that used form validation javascript that worked fine. See below. I changed the page to submit via ajax and now the form validation is skipped. How do I "combine" the two to make it all work? I assume I need to move the validation in the ajax post somehow, but I can't figure it out. Any help would be appreciated.
<form class="card" name="myform" id="myform">
<div class="card-body">
<h3 class="card-title">Add New Blog Post</h3>
<div id='response'></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-label">Blog Title</label>
<input name="subject" type="text" required class="form-control" id="subject" required>
<div class="is-valid"></div>
</div>
</div>
</div>
</form>
<script>
(function() {
'use strict';
window.addEventListener('load', function() {
// Fetch all the forms we want to apply custom Bootstrap validation styles
//to
var forms = document.getElementsByClassName('card');
// Loop over them and prevent submission
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');
}, false);
});
}, false);
})();
</script>
<script>
$(document).on("click","#submitbtn",function(e){
//Prevent Instant Click
e.preventDefault();
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
$("#submitbtn").prop('disabled', true);
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
$("#output").fadeTo(4000, 500).slideUp(500, function(){
$("#output").slideUp(500);
});
$("#myform")[0].reset();
$("#submitbtn").prop('disabled', false);
});
var formData = new FormData($('#myform')[0]);
$.ajax({
url: 'add_blog_do.php',
enctype: 'multipart/form-data',
type: 'POST',
data: formData,
success: function(response) {console.log(response);},
contentType: false,
processData: false,
cache: false
});
});
</script>

You've attached your AJAX call to the click event on your submit button. This fires before the submit event. Since you're invoking event.preventDefault() inside the submit button click handler, the submit event is never running.
You'll want to instead fire your AJAX call in your submit event handler or move it into the click handler. Once the form passes the validity check, you can fire off your actual AJAX call.
An example:
<form class="card" name="myform" id="myform">
<div class="card-body">
<h3 class="card-title">Add New Blog Post</h3>
<div id='response'></div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="form-label">Blog Title</label>
<input name="subject" type="text" required class="form-control" id="subject" required>
<div class="is-valid"></div>
</div>
</div>
</div>
</form>
<script>
$(document).on("click","#submitbtn",function(e){
//Prevent Instant Click
e.preventDefault();
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('card');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
// Check and see if the form is INVALID
// if it is, it currently console logs.
// You may want to do something else here but that's up to you
if (form.checkValidity() === false) {
console.log('Form validation failed')
} else {
// If the form DOESN'T fail, we'll enter this block and run our AJAX
// call as normal
form.classList.add('was-validated');
var formData = new FormData($('#myform')[0]);
$.ajax({
url: 'add_blog_do.php',
enctype: 'multipart/form-data',
type: 'POST',
data: formData,
success: function(response) { console.log(response); },
contentType: false,
processData: false,
cache: false
});
}
});
}, false);
// AJAX Event Listeners for ajaxSend and ajaxComplete
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
$("#submitbtn").prop('disabled', true);
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
$("#output").fadeTo(4000, 500).slideUp(500, function(){
$("#output").slideUp(500);
});
$("#myform")[0].reset();
$("#submitbtn").prop('disabled', false);
});
});
</script>

Related

jquery duplicate ajax request after submit

I have a form that opens inside a BS4 modal window. This contents of the form comes from an AJAX request and that part works fine. However, when I submit the form (again an AJAX request) and it returns some info without closing the modal, and then I submit again, it submits twice. If I submit again, it submits 3 times, etc etc, each time one more submit.
What I missing here? This is my code:
<div id="empModal">
... modal stuff here ...
<div id="NewCustomer" class="col-12 view">
<div id="NewCustomerErrors"></div>
<form name="create_account" class="needs-validation" novalidate>
<div class="form-group">
... form stuff here ...
</div>
<div class="pull-right mt-3">Add new customer</div>
<div class="pull-left mt-3">Back to Log In</div>
</form>
</div>
... modal stuff here ...
</div>
Part 1
$(document).ready(function () {
$("#empModal").on('click', '#customerNewSubmit', function(e) {
$('.needs-validation').on('submit', function(e) {
if (!this.checkValidity()) {
e.preventDefault();
e.stopPropagation();
}
e.preventDefault();
e.stopPropagation();
$(this).addClass('was-validated');
var values = $(this).serialize();
doCreateAccount(values);
});
$('.needs-validation').submit();
return false;
});
});
Part 2
function doCreateAccount(values) {
$.ajax({
url: 'ajax_controller.php',
type: 'post',
dataType: 'json',
data: values+'&act=new',
success: function (res) {
if (res.result_success == true) {
$("#userButton").html(res.result_content);
$('#empModal').modal('hide');
} else {
$("#addNewCustomerErrors").html(res.result_content);
}
},
});
}
from your part 1.
$('.needs-validation').submit();
Comment this code because this is submitting a form again after single submission.

Django : Ajax form still reloads the whole page

I am using a django form with ajax using this code:
<form id="form-id">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
and the Javascript code:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
});
But here is the thing, everytime the submit event is triggered, I feel like the whole page is reloaded (it blinks). What could I do to prevent this from happening?
Your change event is submitting your form and page refreshes. Delete it and add change event to second function, where you're currently waiting for submit event.
$('#form-id').on('change', function(evt) {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
To prevent submit on enter, add keypress event to function and detect when enter is pressed. Like this:
$('#form-id').on('change keypress', function(evt) {
var key = evt.which;
if (key == 13) {
return false;
} else {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
}
});
Key number 13 is enter. When it's pressed, nothing is returned. You could have also replaced return false with evt.preventDefault(). And for other keys, Ajax will be triggered.
What if you add:
return false;
To your code, like so:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
return false;
});
});
Got this from:
https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
A very important detail here: in the end of the function we are
returning false. That’s because we are capturing the form submission
event. So to avoid the browser to perform a full HTTP POST to the
server, we cancel the default behavior returning false in the
function.
How I specify my form in html / django template:
<form id="form-id" action="required-url-goes-here" method="post">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
The tutorial I pointed to above works in a different way then you do. It specifies, inside the ajax request:
- url
- type
- data
- dataType
It also uses a different way to reference the form, and it is the only way I know, so I can't judge if there is an error in the rest of your code.

JavaScript return false is not working

I'am trying to use google invisible reCAPTCHA with AJAX. But returne false is not working.
JS:
function onSubmit(token) {
var siteurl= 'http://localhost/test/';
document.getElementById("register").submit();
var formdata = $('.register').serialize();
$.ajax({
method: "POST",
url: siteurl+"app/ajax/test.php",
data: formdata
})
.done(function( msg ) {
alert(msg);
});
return false
}
HTML:
<form id="register" action="" method="post" class="register">
<input class="for-1" type="text" name="field" >
<input class="g-recaptcha" data-sitekey="6LfCqCAUAAAAAAjaAg5w_mHK" data-callback='onSubmit' type="submit" value="Submit">
</form>
this codes working well but not returning false.
iam waiting help,
thanks.
Well if you wan't to avoid your page from reloading when form is submitted
I suggest you use this flow
1 -> data-callback='onSubmit' attribute is no longer need
2 -> remove function onSubmit and replace it with event listener
this code will listen if your form register is being submitted
$(document)
.off('submit', '.register')
.on('submit', '.register', function(e) {
/** Do what you want when submitting the form **/
var siteurl= 'http://localhost/test/';
var formdata = $('.register').serialize();
$.ajax({
method: "POST",
url: siteurl+"app/ajax/test.php",
data: formdata
})
.done(function( msg ) {
alert(msg);
});
/** prevent form from submitting to your form action page **/
e.preventDefault();
});
3 -> also document.getElementById("register").submit(); remove this since your form is already been submitting
e.preventDefault(); what this line do is it will prevent form from submitting to your form action page

how to get ajax response to trigger click

I have two forms for buy now and for pincode when I click buynow button sending request through ajax and same thing is done for pincode form also.
HTML
<form method="POST" action="/cart/add" id="myForm">
.....
....
<input type="button" class="buyNowBtn" id="btnBuyNow"/>
</form>
<form action="#">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
In the same buynow click event I need to trigger a pincode submit button, so I did this
(document).on('click', '#btnBuyNow', function (e) {
....
....
$("#pinCheckTest").trigger('click');
....
});
the above trigger event is successfully calling pincode click event
$('#pinCheckTest').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {
}
else{
}
}
});
but I need to get ajax response back to trigger event so that I can do some operation is it possible?
something like
(document).on('click', '#btnBuyNow', function (e) {
....
....
$var output=$("#pinCheckTest").trigger('click');//I need to get ajax response back to this click
if(output=='true'){
......
}else{
.....
}
....
});
You can define a variable outside of both click handlers, when .trigger() is called, assign $.ajax() to variable, use .then() within first click handler to process results of $.ajax() call.
Note, included event.preventDefault() to prevent submission of <form>, as pointed out by #IsmailRBOUH
var dfd;
$(document).on('click', '#btnBuyNow', function (e) {
e.preventDefault();
....
....
$("#pinCheckTest").trigger('click');
if (dfd) {
dfd.then(function(output) {
// do stuff with output
console.log(output)
})
}
....
});
$('#pinCheckTest').click(function (e) {
e.preventDefault();
dfd = $.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {}
else{};
}
})
});
var dfd;
$("#first").click(function() {
$("#second").trigger("click");
if (dfd) {
dfd.then(function(data) {
alert(data)
})
}
})
$("#second").click(function() {
// do ajax stuff
dfd = $.when("second clicked")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first">first button</button>
<button id="second">second button</button>
Since you are binding the click event to a button inside form you have the prevent the default behaviour which is 'submit the form'. Change you code to :
$('#pinCheckTest').click(function (e) {
e.preventDefault();
//Your ajax call
});
Here is a demo to clarify the difference https://jsfiddle.net/qvjjo3jk/.
Update1:
Add an id to your form:
<form action="#" id="pinCheckForm">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
Then:
$('#pinCheckForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: url,
data: $(this).serialize(), //Sends all form data
success: function(output) {
if (output == 'true') {} else {}
}
});
});

submitting a form via AJAX

I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});

Categories