Add clear form and hide div when button clicked - javascript

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.

Related

Not able to submit or not submit form after ajax response

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.

Ajax form submit preventDefault() doesnt work

So basically i want to show a loading gif before the content of the page is shown. So i made two divs like this.
<div id="wait"><img src="img/loading.svg" style="width:max-width;height:50px;"></div>
<div id="content"></div>
And i added some javascript to hide the loading gif and show the content as shown below
$('#content').css('display', 'none');
$(document).ready(function() { setTimeout(function() {
$('#wait').css('display', 'none');
}, 3000);
setTimeout(function() {
$('#content').load('portfolio.html');
}, 3100);});
Now when i do this, the form ajax shown below doesnt work.
$(document).ready(function() {
//Validate Form Start
var form = $('#form');
form.submit(function(evt) {
evt.preventDefault();
evt.stopPropagation();
console.log(form.serialize());
$.ajax({
type: 'POST',
url: form.attr("action"),
data: form.serialize(),
success: function(response) {
console.log("Email Sent.");
$('.form').html('Message Sent! Await response.');
$('.form').attr('class', 'btn btn-success btn-lg btn-block form');
function submitTimeout() {
$('.form').html('Send Another Message?');
$('.form').attr('class', 'btn btn-danger btn-lg btn-block form');
}
setTimeout(submitTimeout, 3000);
form.each(function(){
this.reset();
});
}
});
});
//Validate form end.});
It doesn't use ajax to submit the form . It uses default submission inspite of mentioning preventDefault() method. Any fixes please?
Add return false; at the end of your submit function. It will do the trick.
I have found that return false on form.onsubmit event works better than e.preventDefault() for this purpose.
Like this:
form.onsubmit = function(evt){
...
$.ajax({ ...
...
// At the end of the function
return false;
}

Duplicate form submission whtn button clicked?

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.
});
});

javascript not posting form with ajax [duplicate]

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;
});
});

check which button has been clicked in javascript when running a php page via ajax

i have a form on a blog post that displays two submit buttons.
One is save and the other is to delete. E.g.:
<form class="updatepost">
<input type="submit" name="saveupdatebutton" class="saveupdatebutton" value="Save">
<input type="submit" name="deleteupdatebutton" class="deleteupdatebutton" value="Delete">
</form>
Currently, i have this for the js:
// JavaScript - Edit Post
$(document).ready(function(){
$(".updatepost").submit(function(){
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $ckEditor = $targetForm.find('.ckeditor'),
blogpost = $ckEditor.val();
// Validation
if (blogpost === '') {
check = false;
$(this).css('border', 'solid 1px red');
} else {
$(this).css('border', 'none');
}
// ... goes after Validation
if (check) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$targetForm.find('.editor').toggle(),
<!-- Check for .buildtext id etc to prevent it showing any other posts when updating it -->
$targetForm.find('#'+response.postid+'').load(''+response.pageurl+' #'+response.postid+''),
$targetForm.find('#'+response.postid+'').toggle(),
$targetForm.find('.edity').toggle(),
$targetForm.find('.saveupdatebutton').toggle(),
$targetForm.find('.deleteupdatebutton').toggle();
else
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
This obviously runs the code when the form is submitted. But i want to run a different js ajax call depending on what button is clicked.
I have tried this:
// JavaScript - Edit Post
$(document).ready(function(){
$(".saveupdatebutton").click(function(){
DO STUFF ETC...
});
});
But that doesnt work. Any help how i can determine which button is clicked and then carry out a different js code.
Could try something like:
$(".saveupdatebutton").click(function(){
$(this).addClass('activeBtn');
});
$(".updatepost").submit(function(){
var isSave= $(this).find('.saveupdatebutton').is('.activeBtn');
if( isSave){
/* save code*/
}else{
/* delete code*/
}
})

Categories

Resources