Ajax form submit preventDefault() doesnt work - javascript

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

Related

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

Add clear form and hide div when button clicked

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.

Bootstrap popover repeats an action/ event twice?

Why Bootstrap's popover repeats an action twice? For instance, I want to submit a form inside the popover's data-content via ajax. It repeats all the form data twice and the posts form twice.
Any idea what I can do about it?
jquery + bootstrap,
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
$('.bootstrap-popover-method').on('shown.bs.popover', function () {
// do something…
console.log(this); // I get twice of the button element <button class="btn btn-default bootstrap-popover-method"...>
console.log($(".btn-submit").length); // I get twice of '1'.
$(".link").click(function(){
console.log($(this).attr("href")); // I get once of 'test.html'.
return false;
});
$(".btn-submit").click(function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
});
bootsrap + html,
<button type="button" class="btn btn-default bootstrap-popover-method" data-title="body" data-container="body" data-toggle="popover" data-placement="bottom">
Popover on bottom
</button>
<div id="popover-content">
hello
<form action="1.php" class="myform">
<input type="text" name="username" value="hello world!"/>
<input type="submit" value="submit" class="btn-submit"/>
</form>
</div>
This happens because popover.content checks if the tooltip is empty or not.
A simple fix would be to add a title attribute to popover.
$('.bootstrap-popover-method').popover({
placement: 'bottom',
container: 'body',
html:true,
title: "New Title",
content: function () {
var p = $(this);
var data = $('#popover-content').html();
$('#popover-content').remove();
p.attr("data-content", data);
p.popover('show');
}
});
https://github.com/twbs/bootstrap/issues/12563#issuecomment-56813015
This might be an old post, but i'm gonna leave here my work around.
I'm using bootstrap 3.3.5.
So the buggy behavior is that on every execution of "popover('show')", Bootstrap calls the rendering function twice, and only the second call is the one that actually renders the popup.
My fix is to return a short html string for the first call, and for the second call i let run the whole rendering function:
jQuery('.bootstrap-popover-method').popover({
html: true,
trigger: 'manual',
content: function(){//This is our rendering function for the popup's content
var __G_bs_popover_shown= jQuery.data(jQuery('body')[0], '__G_bs_popover_shown');
//Create a global variable, attached to the body element, to keep track of the repeating calls.
__G_bs_popover_shown= (typeof __G_bs_popover_shown == 'undefined') ? 1 : (__G_bs_popover_shown + 1) % 2;
//Update the global var
jQuery.data(jQuery('body')[0], '__G_bs_popover_shown', __G_bs_popover_shown);
//return a short string on every first call (this will not be rendered, anyway)
if(__G_bs_popover_shown == 1) return '<div>BLANK</div>';//==>this should not be an empty string!
//PLACE YOUR CODE HERE, E.G. AJAX CALLS, ETC..
//DON'T FORGET TO RETURN THE HTML FOR THE POPUP'S CONTENT!
}
});
I think you need to prevent the default event of the submit button
$(".btn-submit").click(function(e){
e.preventDefault();
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});
$('.bootstrap-popover-method').off('shown.bs.popover')
.on('shown.bs.popover', function (e) {
e.preventDefault();
}
// unbind your submit button click
$(".btn-submit").off('click').on('click',function(){
console.log($(this).closest("form").attr("action")); // I get twice of '1.php'
var form = $(this).closest("form");
console.log(form.serialize()); // I get twice of 'username=hello+world!'
$.ajax({ // it posts twice to 'POST https://localhost/test/2014/css/bootstrap/1.php'
type: "POST",
url: form.attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data){
//alert(data); // show response from the php script.
}
});
return false;
});

Call This Function Outside of Form Submit

I have a submit button at the end of my form that is labeled like this:
<button id="sendbutton" style="margin-left:25px;" class="btn btn-large btn-primary" type="submit">Send Responses</button>
This button calls this script:
<script type="text/javascript">
$(function() {
$('form').unbind('submit').bind('submit', function(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
});
});
</script>
How do I create a button outside of this form structure that will call the same function?
You may create whatever button you'd like, even if its outside of the form. And then, to get that button to do the same thing you could simply do
$('#yourNewButton').click(function(){
$('form').submit();
});
Or, why not wrap up your original logic into its own function
function submitMyForm(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
}
And then
$('#yourNewButton').click(submitMyForm);
$('form').submit(submitMyForm);
You can write a click handler to the new button and in the handler trigger the form submit using script
<button id="test" style="margin-left:25px;" class="btn btn-large btn-primary" type="button">Send Responses</button>
then
jQuery(function($){
$('#test').click(function(){
$('form').submit()
})
})
Rather than make the submit handler an anonymous function you make it a named function
function submitHandler() {
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function () {
alert('Your answers have been saved.');
}
});
return false;
}
then change your code to
$('form').unbind('submit').bind('submit', submitHandler);
That way you can call that function whenever you like simple by writing submitHandler();

Categories

Resources