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>
Related
How can I block submit after click? I have form with button submit with value.
<button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button>
And my JS looks this:
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
return true;
});
});
Button is blocked but form is not submitting, I don't know why?
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
return true;
});
});
Here the line written as return true prevents the form from being sent and leaves it with the true.
This is what should be written.
$(function(){
$("form").submit(function (e) {
$(".btn").attr("disabled", true);
});
});
Edit
Using AJAX
$(function() {
$("#myForm").on('submit', function(event) {
var form = this;
// Prevent native form submit!
event.preventDefault();
// Disable Button
$(".btn").attr("disabled", true);
// Submit form with AJAX
$.ajax({
url: $(form).attr('action'), // URL where we will send the form
data: $(form).serialize(), // Serialize form data automatically,
type: 'POST',
beforeSend: function() {
alert('The form is sent to: ' + $(form).attr('action') + ' \nForm data: ' + $(form).serialize());
},
success: function(response) {
alert(response); //or whatever
},
error: function() {
alert('Failed!\nBecause "' + $(form).attr('action') + '" not a valid URL'); //or whatever
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm" action="//localhost/some-page.html">
<input name="txt" value="TXT" />
<button type="submit" name="submit" value="1" class="btn btn-sm btn-warning" id=""><i class="fa fa-pencil" aria-hidden="true"></I>Save edit</button>
</form>
I thing it is work in your case:
$(document).ready(() => {
$('#yourFormIDhere').on('submit', () => {
$.ajax({
url:"/your_url",
method:"POST",
beforeSend:function() {
$('.btn').attr('disabled', 'disabled');
},
})
});
});
Your question is not really clear,
I don't really understand what you are trying to do.
Do you want the button to be blocked after you click the button and the form to be submitted?
If you are trying to make the form submit then remove
return true;
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.
Here is my code
<form method="post" role="form" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="submit" id="save" name="save" value="Simpan Data Client" class="btn" style="font-size:0.7em; letter-spacing:1px; color:#666666" /> //For save
<input type="submit" id="delete" name="delete" value="Delete Client" class="btn-delete" style="font-size:0.7em; letter-spacing:1px; color:#666666; padding:8px 15px" /> //For Delete
</form>
<script type="text/javascript">
$("#form").on("submit",function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax(
{
url:'Master/Database/Client/RunClient.php',
type: 'POST',
data: formData,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
beforeSend:function()
{
document.getElementById("loading").style.display = "";
},
complete:function()
{
//document.getElementById("loading").style.display = "none";
},
success:function(result)
{
document.getElementById("info").innerHTML = result;
var n = result.search("error");
if(n < 0) /*document.getElementById("form").reset();*/ $(".input").val('');
}
});
});
</script>
I can get all data from inside my form except from Input type submit i make.
I can't use isset($_POST["save"]) and isset($_POST["delete"]) at my RunClient.php
Create separate function for a submit and pass "submit type" depending on what button is clicked;
$('#save').click(function() {
submitForm('save');
});
$('#delete').click(function() {
submitForm('delete');
});
function submitForm(submittype) {
var formData = new FormData();
//push your form data to formData and add the submittype
formData['type'] = submittype
}
in your php file
$submittype = $_POST['type']; // 'save' or 'delete'
if($submittype == 'save') {
//do save action
}
if($submittype == 'delete') {
//do delete action
}
I use to avoid submit inputs and change by buttons.
<button type="button" id="save">SUBMIT</button> //For save
<script type="text/javascript">
$("#save").on("click",function (e)
{
});
</script>
So, if anyone deativates javscript form will not submit.
And you can send the data like this:
data: {
foo: 'var'
foo2: 5
},
EDIT. Sorry missunderstood your question.
Just control with javascript what button is clicked and assign a value with a hidden field.
'$("#form").on("submit",function (e)' replace the function with
$("#save").click(function() {
});
$("#delete").click(function() {
});
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 {}
}
});
});
i have a live chat messaging system whenever user press enter button it refreshes the page i have tried using prevent default code also but did not worked for me.... here is the code and if there is any problem in the below code please let me know as i'm totally new to website programming
jQuery(document).ready(function() {
jQuery('.btn-success').click(function() {
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
switch (form_name) {
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
Edited part
<form id="npost" name="npost">
<input class="form-control" placeholder="Type your message here..."
type="text" name="message">
<input type="hidden" name="id" value="1">
<span class="input-group-btn">
<button type="button" class="btn btn-success" title="npost" >Send</button>
if you want to prevent from submitting the form you can use return false if you want to stop executing the function and stop submitting it
You need to use preventDefault in order to stop form submission on clicking enter because by default form gets submitted when anyone presses enter. So use preventDefault like this:
<script type="text/javascript" >
jQuery(document).ready(function(){
jQuery('.btn-success').click(function(e){ // added e
e.preventDefault(); // added this line
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
var message = '';
switch (form_name)
{
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
</script>
Here You should not stop form default action you to prevent enter key default answer here is the code to prevent.
$('#npost').on('keyup keypress', function(e) {
if (e.which== 13) {
e.preventDefault();
return false;
}
});