AJAX Multiple Form Submission - javascript

I'm not a Javascript master however I tried hard to prevent this. This script keeps randomly sending multiple posts. I couldn't manage to stabilize it. Usually works fine and sends one post per click. However sometimes it just decides that it should be posted like 5-6 times... Note that using async: false did not really make any difference. And it prevents me from disabling the button after the submission and its not because of "number of clicks" either. Thanks in advance!
$('#submit').click(function () {
$('#submit').attr("disabled", true);
var personal_text_data = document.getElementById('personal_text').value;
var lang_option_data = document.getElementById('language_option').checked;
$.ajax({
type: "POST",
url: 'send.php',
cache: false,
// async: false,
data: ({
notification_type: notification_type_data,
customer_id: customer_id_data,
personal_text: personal_text_data,
language_option: lang_option_data
}),
success: function () {
delete customer_id_data;
delete personal_text_data;
delete notification_type_data;
delete lang_option_data;
location.reload();
}
});
});

Use e.preventDefault(); to avoid the ajax submission and normal form submit from happening. Also change the click event and make it $('[yourForm]').submit().
$('[selectorToYourForm]').submit(function (e) {
$('#submit').prop("disabled", true);
e.preventDefault();
var personal_text_data = document.getElementById('personal_text').value;
var lang_option_data = document.getElementById('language_option').checked;
$.ajax({
type: "POST",
url: 'send.php',
cache: false,
// async: false,
data: ({
notification_type: notification_type_data,
customer_id: customer_id_data,
personal_text: personal_text_data,
language_option: lang_option_data
}),
success: function () {
location.reload();
}
});
});

Related

Don't reload webpage after flask ajax request

I have this ajax request
$(function() {
$('#left').bind('click', function() {
var form = $('form#data')[0]; //
var formData = new FormData(form);
$.ajax({
url: "{{ url_for('encode') }}",
type: 'POST',
data: formData,
async: false,
success: function (data) {
$("#img-2").attr("src", "{{url_for('static', filename='encoded.png')}}");
$("#diff").show();
},
cache: false,
contentType: false,
processData: false
});
});
});
And this flask function runs when the button is clicked.
#app.route('/encode', methods=['GET', 'POST'])
def encode():
a = request.form['text']
img = request.files['files']
img.save("./static/original.png")
secret = lsb.hide(img, a)
secret.save("./static/encoded.png")
return "ok"
The problem I am having is that the webpage becomes for a split second as it should be the image is set and the button diff is shown. But after that the webpage reloads and resets to the index page. And I do not really know how to prevent that from happening. What am I doing wrong?
Blind guess : your button may be part of a form, so its default behaviour when clicked is to submit the form and reload the page. You can prevent that by using event.preventDefault() :
$('#left').bind('click', function(event) {
event.preventDefault()
......

Jquery is not submitting the form with the custom button

My requirement is to upload a file from a form upon clicking the custom button by using Jquery stuff.
My form details are below:
<form id="CreateAttachmentForm" method="post" enctype="multipart/form-data" action="../../FileUploadServlet" >
My file is defined as below:
<input type="file" id="fileupload1" name="fileupload1" accept="image/*,application/pdf" "/>
My custom button related code is below:
<contact:contactbutton
id="printButton"
style="position:relative; width:90px; top:27px; height:30px; left:160px;"
textTop="7px"
defaultButton="false"
tabindex=""
accesskey="C"
onClickEx="createAttachmentRequest();"
onfocus="if(event.altKey){click();}">
<u>C</u>reate
</contact:contactbutton>
Whenever the user clicks on the custom button, the form should be submitted.I have registered an onClick event event where the control should reach the function named createAttachmentRequest()
The following is my createAttachmentRequest() function:
function createAttachmentRequest() {
alert("test ");
$("#CreateAttachmentForm").submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
}
But the form is not submitted when I click the custom button. I have searched various questions on SO, but no suitable solution found so far.However I could see the alert message printed which confirms that the control is reaching the function createAttachmentRequest().What's wrong with my code?
The issue is because you're attaching a submit event handler in the function - not actually submitting the form.
It would be best to remove the createAttachmentRequest() function entirely and use unobtrusive JS code to attach the event. To do that, remove the onClickEx attribute from your <contact:contactbutton> element, then use this JS code:
$(function() {
$("#CreateAttachmentForm").submit(function(e) {
e.preventDefault();
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: new FormData(this),
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
});
Also note that I removed async: false as it's incredibly bad practice to use it. If you check the console you'll even see warnings about its use.
You can do one of the following:
Take the submit event outside the function and remove the function like so:
$("#CreateAttachmentForm").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
OR
inside the function remove the submit listener like so:
function createAttachmentRequest() {
alert("test ");
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}

JQuery form submit not calling success

After click on submit beforeSend: works but it does not call success: also there is no console error . The data also submit to database correctly ! Then why it not call the success: . Please Help
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$(".alert").removeClass("hide");
var msg = $.ajax({
type: "GET",
url: actionurl,
async: false
}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function() { // wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
});
});
Console Message
Object {readyState: 4, responseText: "<strong>Seat Booked Successfully</strong>", status: 200, statusText: "OK"}
In a Ajax call 'dataType' attributes means what data format can be expect from client(browser). As per error message server is returning 'string' instead 'json'.
But on the other hand, given ajax call is expecting json data to be returned by backend server. Either provide a
valid JSON in response or change datatype to html.
In your AJAX call settings you set dataType to json, but in return you provide a string.
dataType (default: Intelligent Guess (xml, json, script, or html)) The
type of data that you're expecting back from the server. If none is
specified, jQuery will try to infer it based on the MIME type of the
response
So, you have two solutions:
Provide a valid JSON in response
Do not ask for JSON by changing your dataType value (to html), or by removing it.
I had similar problem. As you are redirecting page in success you need to use
e.preventDefault(); // to prevent page refresh
after the ajax call or
return false; // to prevent page refresh
Something like this :
$(function() {
//hang on event of form with id=ticketForm
$("#ticketForm").submit(function(e) {
//prevent Default functionality
e.preventDefault();
//get the action-url of the form
var actionurl = e.currentTarget.action;
var form = $('#ticketForm');
var submit = $('#submite');
$.ajax({
url: actionurl,
type: "POST",
data: $("#ticketForm").serialize(),
dataType: "json",
contentType: 'application/json; charset=utf-8',
cache: false,
beforeSend: function(e) {
submit.html("Booking....");
},
success: function(e) {
submit.html("Booking Completed !");
//get the message from booking.php and show it.
$( ".alert" ).removeClass( "hide" );
var msg = $.ajax({type: "GET", url: actionurl, async: false}).responseText;
document.getElementById("success-message").innerHTML = msg;
setTimeout(function(){// wait for 3 secs(2)
location.reload(); // then reload the page.(3)
}, 3000);
},
error: function(e) {
console.log(e)
}
});
return false; e.preventDefault(); //any one of this options to prevent page refresh after ajax call
});
});

Ajax call multiple time onclick event on bootstrap modal

By clicking a button Its loaded a bootstrap modal. On the modal there have a form and on click save button I am trying to submit form by ajax call. At first time the ajax call trigger one time, but 2nd time the ajax url trigger two times. I see on firebug console section the post url is called multiple times.
Here Is my jquery code.
$(".show-modal").click(function() {
$('.upload-modal').modal();
$(".save-logo").click(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
data : data,
contentType: false,
cache : false,
processData: false,
url : "../../io/upload/"
}).done(function(rawData) {
$('.modal-header .close').click();
})
});
})
The problem is that you have your .save-logo click handler inside the .show-modal click handler. So every time the modal is shown, you attach another click handler to the .save-logo element. The code below should fix that problem:
$(".show-modal").click(function () {
$('.upload-modal').modal();
});
$(".save-logo").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
data: data,
contentType: false,
cache: false,
processData: false,
url: "../../io/upload/"
}).done(function (rawData) {
$('.modal-header .close').click();
})
});
$(function(){
var editUserId;
$('#edit-user-modal').on('show.bs.modal', function(e) {
editUserId = $(e.relatedTarget).data('userid');
});
$("#edit-user-form").submit(function(event) {
event.preventDefault();
var form = $(this);
var route = "/edit-user/" + editUserId;
if(validateEditUserForm()){
$.ajax({
type: "POST",
url: route,
data: form.serialize(),
success: function(Response)
{
if(Response){
console.log(Response.status);
console.log(Response.message);
if(Response.status == 'success'){
$('#adduser-alert-box').hide();
$("#add-user-form")[0].reset();
$('#adduser-success-box').show();
$('#adduser-success-box').html(Response.message);
}
else{
console.log('User could not be added');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html(Response.message);
}
}
else{
console.log('No Response');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('No Response');
}
}
});
}
else{
console.log('Validation Error');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('Please Fill All the Fields Correctly');
}
});});
I faced the same issue and randomly i tried something .
so if you create a global variable to store the 'id' you pass from your button then store the id from the 'data' attribute of your button then it won't make multiple requests when clicked since you have declared the variable globally!
Hope it helps.

How to make a form wait for ajax to finish before it submits?

So there is a form that i want to submit only when a condition is verified from the database using ajax. I am using preventDefault() method if the condition is true i.e. if a user is not a resident, a variable is set to true in ajax successs function and preventDefault() gets called, however, when doing this, the form always submits. It doesn't wait for the ajax to finish even when async is set to false.
Here's the code.
$('#button').click(function(e) {
if ($('#ca_resident').prop('checked') == true) {
amount=$('#user-amount').val().replace(/[,]/g,"");
project_name=$('#project_name').val();
var not_resident = false;
$.ajax({
url: '/main/verify_residence/',
type: 'POST',
aysnc: false,
data: {
value: amount,
name: project_name
},
success: function(data){
$("#verify_residence").html(data);
not_resident = true;
},
dataType: 'html'
});
}
if(not_resident){
e.preventDefault();
}
});
that won't work. Success will fire after:
if(not_resident){
e.preventDefault();
}
As it's asynchronous. You need to always cancel the button click then submit the form once success is hit:
$('#button').click(function(e) {
var $form = $(this).closest('form');
if ($('#ca_resident').prop('checked') == true) {
amount=$('#user-amount').val().replace(/[,]/g,"");
project_name=$('#project_name').val();
$.ajax({
url: '/main/verify_residence/',
type: 'POST',
aysnc: false,
data: {
value: amount,
name: project_name
},
success: function(data){
$("#verify_residence").html(data);
$form.submit();
},
dataType: 'html'
});
}
e.preventDefault();
});

Categories

Resources