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;
Related
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 code to load my bookmark.php via AJAX when clicking submit but when I'm clicking it alert was popping up but bookmark.php is not working properly.
Here is my code in below:
What am I missing ?
PHP:
require_once 'class.trip.php';
$trip = new TRIP();
$save = $trip->saveTrip();
HTML/AJAX:
<script type="text/javascript">
$(function () {
$('#joinform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'bookmark.php',
data: $('#joinform').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
<form id="joinform">
<input name="submit" type="submit" class="btn btn-success btn-lg" value="Join This Trip"/>
</form>
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 need to check whether the data is already exists in the database before submitting the form using ajax. The most common scenario is the checking the availability of the username and email.
It's not working but I tested the ajax function without using the from control and it works fine. The project is created in MVC 3 VB.
Javascript:
$('#addSalesPeople').click(function () {
$.post("ajax_functions/checkDuplicate.cshtml",
{
extension: document.getElementById('Extension').value,
initials: document.getElementById('Initials').value
},
function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
});
HTML:
#Using Html.BeginForm("Create", "SalesPeople", FormMethod.Post)
#Html.ValidationSummary(True)
#<fieldset>
............................
..............................
#Html.TextBoxFor(Function(model) model.Extension, New With {.onkeyup = "javascript: charCounter(this,4);", .onblur = "javascript: zeroPad(this, 4)"})
#Html.TextBoxFor(Function(model) model.Initials)
<input id="addSalesPeople" class="btn span2" type="submit" value="Add" />
</fieldset>
-Thanks
You need to observe the submit event of the form.
Instead of
$('#addSalesPeople').click(function () {
use
$('#theFormId').submit(function () {
see: http://api.jquery.com/submit/
You can also disable the form submit and send it later manually:
$( '#theFormId' ).submit( function ( event ) {
event.preventDefault();
/* your AJAX code */
$( '#theFormId' ).submit();
} );
I am posting a real tested code.
HTML: Simple form post button in #using
(Html.BeginForm())
{
//use your text box or other control here
<input type="submit" id="Create" value="Create" class="btn btn-primary" />
}
JavaScript:
<script>
$(document).ready(function () {
$("form").submit(function (e) {
e.preventDefault(); //prevent default form submit
if ($(this).valid()) {
var UserId= $('#UserId').val();
$.ajax({
url: '/Home/CheckUserExist/', //ControllerName/ActionName/
data: {
UserId: UserId
},
success: function (data) {
showMsg(data);
},
cache: false
});
}
});
});
function showMsg(hasCurrentJob) {
if (hasCurrentJob != "OK") {
alert(hasCurrentJob);
return false;
} else {
//if check is ok than from post to controller
$("form").unbind('submit').submit();
}
}
</script>
MVC Controller:
public async Task<JsonResult> CheckUserExist(int UserId)
{
//condition for user check
if (UserExist==true)
{
return Json("User Exist Please choose another user name or etc", JsonRequestBehavior.AllowGet);
}
return Json("OK", JsonRequestBehavior.AllowGet);
}
if you have any query mail me vishalroxx7#gmail.com.
I am having an infinite cycle using this jquery code, I know WHY but I dont know HOW to fix this:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true")
$('#submitme').submit();
});
});
</script>
The jQuery.validate plugin takes care of this and I would strongly recommend you using it:
$('#submitme').validate({
rules: {
n1: {
remote: {
url: 'validate.php',
type: 'post'
}
}
}
});
But if you don't want to use it another possibility is to use a global variable, like so:
$('#submitme').submit(function() {
if (!$.formSubmitting) {
var $form = $(this);
$.post('validate.php', { value: $('#n1').val() }, function (data) {
if (data == 'true') {
// set the global variable to true so that we don't enter
// the infinite loop and directly submit the form
$.formSubmitting = true;
$form.submit();
}
});
return false;
}
return true;
});
Just a remark: the button you have placed inside the form is not a submit button so clicking it will not trigger the submit handler. You should make it a submit button:
<input value="Send" type="submit" />
I am not a jQuery expert, but in Prototype, when you write an event handler for an action and you don't stop the default action, than it will be executed after all of your callback functionality was done. So by simply flipping the if-else statement you should be able to avoid a infinite loop:
$('#submitme').bind( 'submit', function(event) {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data != "true")
// if validation has failed, prevent default action (submit)
event.preventDefault();
});
// if default action was not prevented it will be executed
})
I found this solution:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
if ($.data( $('#submitme' ), 'validated'))
return true;
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true") {
$.data( $('#submitme'), 'validated', true );
$('#submitme').submit();
}
});
return false;
});
</script>