I have a form in HTML where I have used onsubmit to validate input and action to call the URL on form submit. This is my HTML code:
<form method="POST" onsubmit="return validateInput();" action="editConf" id="edit-form">
// HTML Form code
<div class="modal-footer">
<p id = "edit-footer" align="center"> </p>
<button type="reset" onClick="resetForm()" class="btn btn-secondary" data-dismiss="modal" >Cancel</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
This is my script code:
function validateInput() {
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: { data: document.getElementById('data') },
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
return true;
} else {
return false;
}
}
});
I am facing the issue that the URL in action completes its execution first so even if the form is not valid it is submitting. How to solve this issue ?
Since $.ajax is asynchronous, you can't use the return value of the success function.
You need to prevent the default submission immediately, then call submit() in the success function.
Also, in the data: option you need to get the value of an input, the input element itself.
function validateInput() {
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: {
data: $("#data").val()
},
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
$("#edit-input").submit();
}
}
});
return false;
}
To prevent this from looping infinitely, because submit() runs the same validation function first, remove onsubmit from the form, and move it to the submit button.
<button type="submit" class="btn btn-primary" onclick="return validateInput();">Save changes</button>
You should prevent default event if you want to have custom async validation.
<form id="myForm" method="POST" action="editConf" id="edit-form">
fix your script to
$('#myForm').on('submit', validateInput)
function validateInput(event) {
event.preventDefault(); //Here we stoped defauld submit event
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: { data: document.getElementById('data') },
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
return true;
} else {
return false;
}
}
});
Now the form won't be submitted. But now you have to think how you want to send data of the form to the server. There are several variants.
1) You can get form data and send it with ajax imitating the form
2) You can store a flag somewhere marking your form valid and if it is valid don't stop submit the form from your script and don't stop the event.
Related
I am trying to submit a form with a little error handling. when the fields are empty there will be a warning and it shouldn't be saved on DB. if the fields are filled there should be a success alert. My case is still the empty value is being saved.
HTML
<input type="submit" id="add" onclick="emptyHandling();" name="_add" class="btn btn-primary btn-size" value="Add"/>
//FORM SUBMIT
$(document).ready(function(){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'add.php',
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
async: false,
autoUpload: false,
success: function(response){
$('.statusMsg').html('');
if(response.status == 1){
$('#form')[0].reset(); //FORM TO RESET AFTER SUBMISSION
$('.statusMsg').html('<p class="alert alert-success">'+response.message+'</p>'); // REPONSE MESSAGE
}else{
$('.statusMsg').html(alert(response.message));
}
$('#form').css("opacity","");
$(".submit").removeAttr("disabled");
}
});
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling(){
var inv = $("#inv").val();
if(inv == ''){
var message = "Field Left Empty";
alertMessage(message);
}else{
successMessage();
}
return false; // THIS IS BEING RETURNED FALSE
}
//WARNING ALERT
function alertMessage(titleMessage){
swal({
title: titleMessage,
text: "Mandatory Fields are Required to be Filled",
type: "warning",
confirmButtonClass: "btn btn-danger"
});
}
The return is made false on error handling which should stop the next processes. I am not really sure of where the mistake is made.
You can remove onclick from your submit button and move that function call inside your form submit handler . Then , inside this check if the validation function return true/false depending on this execute your ajax call.
Demo Code :
$(document).ready(function() {
$("#form").on('submit', function(e) {
e.preventDefault();
//call function..
if (emptyHandling()) {
//your ajax...
console.log("inside ajax....")
}
});
});
//ERROR HANDLING - TRIGGERED ON CLICK
function emptyHandling() {
var flag = true
var inv = $("#inv").val();
if (inv == '') {
var message = "Field Left Empty";
alertMessage(message);
flag = false
} else {
successMessage();
}
return flag; // return flag//
}
//WARNING ALERT
function alertMessage(titleMessage) {
//swal...
console.log(titleMessage)
}
function successMessage() {
console.log("All good...")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<form id="form">
<input type="text" id="inv">
<input type="submit" id="add" name="_add" class="btn btn-primary btn-size" value="Add" />
</form>
In my form i am checking if there is same value in database or not when form submitted. The code below works fine and is giving the rigth result of AJAX post but the problem is when giving alert according to the wrong result, javascript alert and focus works but form still submits after these.
Button for submit:
<input type="submit" name="kaydet" class="btn btn-success form-control"
onClick="return kaynak_kontrol()" value="Kaydet">
AJAX:
<script type="text/javascript">
function kaynak_kontrol(){
Form=document.forms['depo_kayit'];
var depo_sube_no = document.getElementById('depo_sube_no').value;
var depo_firma_no = document.getElementById('depo_firma_no').value;
var depo_kodu = document.getElementById('depo_kodu').value;
var dataString ="depo_sube_no="+depo_sube_no+"&depo_firma_no="+depo_firma_no+"&depo_kodu="+depo_kodu;
$.ajax({
type: "POST",
url: "depo_kodu_kontrol.php",
data: dataString,
success: function(result){
if(result != 0){
alert("Aynı şubede aynı isimde iki depo olamaz!");
document.getElementById('depo_kodu').focus();
return false;
} else {
return true;
Form.submit();
}
}
});
}
</script>
Can you help me why i return false is not working and form still submits?
you need to prevent the form submission manually using jQuery event.preventDefault()
here is a small fix
function kaynak_kontrol(event){ // notice the new parameter !
event.preventDefault();
//the rest of your code
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 {}
}
});
});
Below is my code of html and jquery, i want to dsiplay results on submit button on the same page rather than its goes on next page. But it is not returning me any results and go to next page.
HTML code
<form id="create" action="/engine_search/search/" method="get">
<input style="height:40px;" type="text" class="form-control" placeholder="Search" name="q">
<center>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search">
</center>
</form>
jquery code:
<script>
$(document).ready(function() {
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search" onclick="return SubmitFunction(this);">
Javascript :
function SubmitFunction(thisId){
$.ajax({ // create an AJAX call...
data: $(thisId).serialize(), // get the form data
type: $(thisId).attr('method'), // GET or POST
url: $(thisId).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
}
You should use event.preventDefault();
<script>
$(document).ready(function() {
$('#create').submit(function(event) { // catch the form's submit event
event.preventDefault();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
Look for console for any errors. It might be helpful.
I am trying to submit a form through ajax function while button
but on safari browser its submitting like a normal form submitting.
and In other browser its working properly through ajax function
<g:form action="addEmpHistory" name="formNew" method="post">
<button id="submitBtn" name="submitBtn" onclick="submitform(formNew);"></button>
</g:form>
//Ajax code
function submitform(data){
$("#"+data).submit(function(event) {
new Event(event).preventDefault();
event.preventDefault();
$.ajax({
type: 'POST',
url: '/user/addUSer',
data: $('#'+data).serialize(),
success: function (data) {
location.reload();
}
});
});
}
Seen as you are using jQuery, consider removing onclick
<form action="addEmpHistory" id="formNew" name="formNew" method="post">
<button id="submitBtn" name="submitBtn">Submit</button>
</form>
and replacing your submitform function with jQuery event binding, something like:
$(document).ready(function() {
$("#formNew").submit(function() {
$.ajax({
type: 'POST',
url: '/user/addUSer',
data: $("#formNew").serialize(),
success: function(data) {
alert(data);
}
});
return false; // prevent actual form submit
});
});