This question already has answers here:
Duplicate form submission whtn button clicked?
(2 answers)
Closed 5 years ago.
I have a javascript to post a form using ajax but it keeps giving me an error. It is triggered from a bootstrap button but does not seem to do anything?
The button is :
<button id='btn-finish' name ='btn-finish' type='button' class='btn btn-primary'>Finish</button>
and the js is :-
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('process-form3.php'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
// $('#5box').hide();
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
You must have to get Form id not a button Id, you have written code for getting button id instead of form object.
code should be like for example:
<form id='test_form' action='path' method='post'>
<button id='btn-finish' name ='btn-finish' type='button' class='btn btn-primary'>Finish</button>
</form>
your jquery code :
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $('#test_form');
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
// $('#5box').hide();
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
Related
I am trying to submit a form after validation and confirmation. But after the validation the form is not getting submitted. If I do not validate and confirm then the form is being submitted. What am I doing wrong here? Please tell me how to rectify it.
<div class="button secondary" id="contact_submit">
Create/Update <span class="icon-right icon-check"></span>
</div>
function validateFields() {
#some validation operations
if(validated){
if(operation == "Create"){
$("#contact-form")[0].setAttribute("action", "/contact/create_contact/");
$("#contact-form")[0].setAttribute("method", "POST");
}
else if(operation == "Update"){
$("#contact-form")[0].setAttribute("action", "/contact/" + object_id + "/update_contact/");
$("#contact-form")[0].setAttribute("method", "PATCH");
}
$('#contact-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '/oms/getIsPrimaryContact/',
type: 'GET',
data: { object_id: object_id },
success: function(data) {
if ($('.element-contact#is_primary_contact').prop("checked") && !data.is_primary_contact) {
var c = confirm('Are you sure you want to change the primary contact?');
if (c) {
return true;
} else {
return false;
}
}
},
error: function() {} });
});
$('#contact-form').submit();
}
}
$(document).ready(function(){
$("#contact_submit").click(function(e) {
validateFields()
});
});
It just shows the confirmation box and if I click on ok or cancel then also the ajax call is being initiated. If the checkbox is not checked then also the form is not being submitted.
On clicking either button in the confirmation box the form should be submitted or not submitted and if the checkbox is not checked then the form should just be submitted.
But instead ajax call is happening on clicking any button.
I had a problem earlier that seemed to be solved but on closer inspection it is not fully fixed. I have a button that when clicked activates a javascript to send form data, then clear the form and then close hide the div. It works great apart from when I check the database it seems to submit twice? I have looked and cant see where the problem lies?
The button is :
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
and the new JS code that duplicates entry is :
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
});
});
});
and the old js(without clearing form and hiding div but does not duplicate entry) is :
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
Try adding return false to the end of your event handler. How to prevent form from being submitted?
remove button "type =submit" and
then use your old code below.
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
});
});
I have had this issue before but people keep getting my question misunderstood. I will try again. I have a bootstrat button that when clicked javascript sends the form using ajax. It works fine but I cannot add anything to clear the form and then hide the div. I have code that does work but it sends the form twice for some reason(not included but can if you wish)? Sorry to repost similar question but people keep giving me the same code that simply does not work. I think it has something to do with it being a button type?
The JS code is :
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevent default submission of the form after clicking on the submit button.
return false;
});
});
And the button is :
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
Here is a reset form script from w3schools.com that should work
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
document.getElementById(form.attr('id')).reset();
document.getElementById(form.attr('id')).style.display="none";
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevent default submission of the form after clicking on the submit button.
return false;
});
});
Here's the code that works making fake AJAX request. It replaces output_message with Processing... and replaces with Message Sent! once complete.
$(document).ready(function() {
$('#btn-finish').on('click', function(event) {
event.preventDefault();
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
setTimeout(function() {
console.log("fake ajax");
$('.output_message').text('Message Sent!');
// This will clear out form field values.
// resetForm($('#myform')); // by id, recommended
// This will hide your element
// $('#myform').hide();
}, 5000);
});
});
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn-finish" name='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
<div class="output_message"></div>
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
//code to clear form and hide div comes here
$("#divid").hide();
} else {
$('.output_message').text('Error Sending email!');
}
},
complete: function(){
//code to clear form and hide div comes here
$("#divid").hide();
}
try placing the code to hide and clear the form as mentioned above in success. If ajax response is success or error, by default if you want to hide then use the code in complete function as above.Post your comments.
Before posting to this question i checked below links.
How do I use two submit buttons, and differentiate between which one was used to submit the form?
Two submit buttons in one form
but i am still facing issue.
Below are the codes.
html code
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
Here is the php code on posting_bk.php
if (isset($_POST['publish'])) {
# Publish-button was clicked
array_push($res['errors'], 'Publish button');
echo json_encode($res);
}
elseif (isset($_POST['save'])) {
# Save-button was clicked
array_push($res['errors'], 'Save button.');
echo json_encode($res);
}
Issue is i am not getting any output. i was suppose to get test publish or test save.
i am planning to use ajax and below is the code i have written for ajax.
<script type="text/javascript">
$('document').ready(function() {
$("#posting").on("submit", function(e) {
e.preventDefault;
var btn = $('#publish');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: $('form#posting').serialize(),
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
});
</script>
If i didn't use ajax then it is working fine. It seems like issue with Ajax
I will go with a click submit, take the id of the clicked button and pass it to the php :
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url:$('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {data:$('form#posting').serialize(),action:el},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if(data.success == false)
{
var arr = data.errors;
$.each(arr, function(index, value)
{
if (value.length != 0)
{
$("#validation-errors").append('<div class="alert alert-danger"><strong>'+ value +'</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
});
php:
if ($_POST['action'] == 'publish') {
# Publish-button was clicked
echo 'test publish';
}
elseif ($_POST['action'] == 'save') {
# Save-button was clicked
echo 'test save';
}
You can't do it the way you're trying to do it because publish and save will both always be set no matter which button you click on.
You need to do it on the client side. Bind an event listener to each button and that listener will pass whatever "action" variable you want.
If you were using jQuery for example:
$('#publish').on('click', function(e){
e.preventDefault();
// Set some hidden form variable called action to a value of publish
// submit form or make an ajax call.
});
$('#save').on('click', function(e){
e.preventDefault();
// Set some hidden form variable called action to a value of save
// submit form or make an ajax call.
});
Now your PHP can check if $_POST['action'] == 'save'|'publish' and act accordingly.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Disable submit button on form submit
I have a question about disable button after ajax submit.
Actually the button disabled first until I input text to textarea. Then if I submit with click button, it must disable the button.
In my actual, after click button, the button isn't disabled.
Here it's my JS code :
$(function()
{
$("#submit_h").click(function()
{
var haps = $("#haps").val();
var dataString = 'haps='+ haps;
if(haps=='')
{
alert('Please type your haps');
}
else
{
$.ajax({
type: "POST",
url: "post_haps.php",
data: dataString,
cache: false,
success: function(html){
$("#haps").val('');
$("#content").prepend(html);
}
});
}return false;
});
});
--
<textarea id="haps"></textarea>
<input type="submit" class="button inact" value="Share" disabled="disabled" id="submit_h"/>
Now what I want to do is, disabled the button after submit.
Any idea ?
Similar to NullUserException's link, you can use jquery to set the "disabled" attribute:
$(".inact").attr('disabled', 'disabled');
Disable the button in ajax success:
success: function(html){
$("#haps").val('');
$("#content").prepend(html);
$("#submit_h").attr("disabled", true);
}