I am trying to send a html form consisting of more than 100 sub fieldsets of 10 elements which it totally a huge form of more than 1000 elements.
I use jQuery to send this form. The problem is that it doesn't send all of the elements (it sends 84 sub fields out of 100).
I've been searching a lot but I have not found a reason or solution. Is it a limitation of jQuery or HTML or am I doing something wrong?
Here is the jQuery code:
$(document).on("submit", "#video_table", function() {
var action = $(this).attr('action');
var image_load = "<img src='/img/loading.gif' />";
$("#videoupdate-div").html(image_load);
// $.post(action, $(this).serialize(), function(data) {
// $("#videoupdate-div").html(data);
// });
$.ajax({
//dataType: "json",
url : action,
type : "POST",
data : $(this).serialize() ,
success : function(result) {
$("#videoupdate-div").html(result);
},
error : function(result) {
$("#videoupdate-div").html("Error! Something must be wrong.");
}
});
return false;
});
The form's own submission likely interferes with the submit event
Change
$(document).on("submit", "#video_table", function() {
to
$(document).on("submit", "#video_table", function(e) {
e.preventDefault(); // cancel the form's own submit
PS If the form is not dynamically inserted into the DOM, then this is enough
$("#video_table").on("submit", function(e) {
e.preventDefault();
Related
I would like to validate a form with an AJAX request to the server and then swap the form html in the web browser with the form html from the server because this would be an easy implementation in theory. It is proving a nightmare though because the change event is triggered without the user interacting further after the first interaction which triggered the first change event. Consequently an infinite loop of AJAX requests to the server is happening.
The html form sits inside a div which has classes 'container mb-4'. This is the JS code -
var _cont = $('.container.mb-4')
var _form = $('.custom-form')
function ajax_validation(form) {
form.on('change', 'input, select, textarea', function() {
form_data = form.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.empty()
_cont.append(data['form_html'])
form = _cont.find('form')
ajax_validation(form)
}
},
error: function () {
form.find('.error-message').show()
}
});
})
}
ajax_validation(_form)
The change event I am assuming is triggered because the server returns a form input field with a different csrf token as the value to the previous input field - all other fields are the same. So an obvious solution would be to keep the same csrf token. But I want to understand why the JS code isn't working. I thought destroying the form would destroy the change event bound to it. So am at a loss to explain this infinite loop. How do I change this so I can just swap the form and not trigger another change event until the user really does change something?
It's not a good thing to use events in function no need to do that
Also your event here for input , select , textarea for serialize you need to select the closest() form
Try the next code
var _cont = $('.container.mb-4');
var _form = $('.custom-form');
_cont.on('change', 'form input,form select,form textarea', function() {
var ThisForm = $(this).closest('form');
var form_data = ThisForm.serialize();
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.html(data['form_html']);
}
},
error: function () {
ThisForm.find('.error-message').show()
}
});
});
And logically if(!(data['success'])) { should be if(data['success']) {
First let's understand the issue that you have. You have a function called ajax_validation that is defining a change event on the form's elements which, on response will call ajax_validation. So, if any change happens on your elements, then a new request is sent to the server. So, if any value is changed, like a token, the request will be sent again. You could use a semaphore, like this:
var semaphore = true;
function ajax_validation(form) {
form.on('change', 'input, select, textarea', function() {
if (!semaphore) return;
semaphore = false;
form_data = form.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.empty()
_cont.append(data['form_html'])
form = _cont.find('form')
ajax_validation(form)
}
semaphore = true;
},
error: function () {
form.find('.error-message').show()
}
});
})
}
Something like this should solve your issue for the time being, but you should consider refactoring your code, because what you experience is well-known and is called callback hell.
Turns out the password field was coming back blank from the server - this django must do out of the box if the PasswordInput widget is used. So the form is replaced with a new form which lacks the password input from the before. The browser was then applying the autofill password value to the form which was triggering the change event.
This is my code now. It checks that the form_data about to be sent for validation really is different to before minus the csrf token which will be different.
It is based on Mohamed's answer -
var _cont = $('.container.mb-4');
var _form = $('.custom-form');
var prev_data = undefined
_cont.on('change', 'form input,form select,form textarea', function() {
var ThisForm = $(this).closest('form');
var form_data_wo_csrf = ThisForm.find("input, textarea, select").not("input[type='hidden']").serialize()
if(form_data_wo_csrf == prev_data) {
return
}
var form_data = ThisForm.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.html(data['form_html']);
prev_data = form_data_wo_csrf
}
},
error: function () {
ThisForm.find('.error-message').show()
}
});
});
I have a script that sends my form via php-ajax. It does return success but what I need it to do when it has been successful is clear all the form data and close the div and load another one. I have tried many different ways to clear form and close div but they just seem to stop it working totally. The id of the div to close is '5box' The working script that i need to add these to 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;
});
});
Any ideas would be appreciated
To clear the form you can call the reset() method of the underlying Element. I'm not sure what you mean by 'close the div', but you can call hide() to make it disappear. Try this:
success: function(result) {
if (result == 'success') {
$('.output_message').text('Message Sent!');
form[0].reset();
$('#5box').hide();
} else {
$('.output_message').text('Error Sending email!');
}
}
Also note that it would be much better practice to return JSON from the AJAX call. You can then have a boolean flag to show the state of the request.
Update
<button name ='send' value="Send" type='submit' class='btn btn-primary'>Finish</button>
Given that is the code of your button there is another issue - you're not preventing the form from being submit, hence the AJAX request is cancelled. To do this, hook to the submit event of the form instead of the click of the button. From there you can call e.preventDefault() to stop form submission. Try this:
<script>
$(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!');
}
}
});
});
});
</script>
Note I used a generic 'form' selector above. You can change that to a class or id selector on the form as required.
For clearing form fields
$("input[type=text], textarea").val("");
cheers
you can also use Triggers as well
$('#form_id').trigger("reset");
I have the following code which is supposed submit a form via Ajax without having to reload the page:
$( document ).on('submit', '.login_form', function( event ){
event.preventDefault();
var $this = $(this);
$.ajax({
data: "action=login_submit&" + $this.serialize(),
type: "POST",
url: _ajax_login_settings.ajaxurl,
success: function( msg ){
ajax_login_register_show_message( $this, msg );
}
});
});
However for some reason, despite the event.preventDefault(); function which is supposed to prevent the form from actually firing, it actually does fire.
My question is, how do I prevent the above form from reloading the page?
Thanks
don't attach a listener on document instead use a on click handler on the submit button and change the type to button.
<button id="form1SubmitBtn">Submit</button>
$('#form1SubmitBtn').click(function(){
//do ajax here
});
Happy Coding !!!
for instance you can write like this
$(".login_form").on('submit', function( event ){
var $this = $(this);
$.ajax({
data: "action=login_submit&" + $this.serialize(),
type: "POST",
url: _ajax_login_settings.ajaxurl,
success: function( msg ){
ajax_login_register_show_message( $this, msg );
}
});
event.preventDefault();
});
You can use jquery and ajax to do that. Here is a nice piece code below that doesn't refresh the page but instead on submit the form gets hidden and gets replaced by a thank you message. The form data is sent to an email address using sendmail.php script.
Assuming your form has 3 input fields - name, email and message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function() {
jQuery("#button").click(function() {
var name=jQuery('#name').val();
var email=jQuery('#email').val();
var message=jQuery('#message').val();
var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
jQuery.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function() {
jQuery('#contact_form').html("<div id='message'></div>");
jQuery('#contactForm').hide();
jQuery('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Thank you for your submission. We will be in touch shortly.</p>").hide()
.fadeIn(1500, function() {
});
}
});
return false;
});
});
</script>
On top of your form tag just add this to display the thank you message.
<div id='message'></div>
Enjoy coding!!!!!!!
I'm planning on saving 2 forms but the 1st form is where I get the Foreign key for the Second form.
This is my Attempt to save this Using Javascript:
$("#btnSave").click(function (e) {
e.preventDefault();
$('#workForm').submit();
$('#contForm').submit();
});
But it errors on Contact Form Submit in the control because the ID of Worker Form is still null while saving the contact form that is its Foreign Key
How can I Handle This using Jquery and Javascript and Ajax?
I also Tried this method:
$("#btnSave").click(function (e) {
e.preventDefault();
if (Id != 0) {
$('#workForm').submit();
$('#contForm').submit();
} else {
$('#workForm').submit(); }
});
But it only goes at Else because the ID is null
I hope someone can help me here
Worker Address is the WorkForm Worker Contact is the ContForm
I want to save them both when they populate all the textbox
You will have to use ajax because
$('#contForm').submit();
will never be run as the page will be unloaded by the first call:
$('#workForm').submit();
You can submit the first form using ajaxSubmit() and on its success, submit the second form.
$("#btnSave").click(function() {
$('#workForm').ajaxSubmit({
forceSync: true,
error: function(errorDetails) {
//Error Handling
},
success: function(successData) {
$('#contForm').submit();
}
});
});
You need to post both forms using .ajax. Serialize the data from both forms and then post to your server script.
$("#btnSave").click(function (e) {
e.preventDefault();
//Serialize the form data
var formOne$ = $('#workForm').serialize();
var formTwo$ = $('#contForm').serialize();
$.ajax( { url : "YOURURL", type: 'post', data : { formOne : formOne$ , formTwo : formTwo$ },
success : function( responseText ){
//Forms were submitted
},
error : function( e ){
alert( ' Error : ' + e.statusText );
}
});
});
I have a form that, when submitted, goes through the usual e.preventDefault() and sends an ajax request instead. However, if this ajax request returns a certain condition, I want the form to be submitted normally. How do I achieve this?
// Submit handler
$(".reserveer_form").submit(function(event){
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(data) {
if($(".messagered",data).length > 0){
var errors = $(".messagered",data);
$(".gegevens").before(errors);
} else {
// SUBMIT THE FORM!
}
}
});
})
Invoke the native submit method on the form, so that it doesn't trigger the jQuery handler.
$.ajax({
context: this, // <-- set the context.
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
if ($(".messagered", data).length > 0) {
var errors = $(".messagered", data);
$(".gegevens").before(errors);
} else {
this.submit(); // <-- submit the form
}
}
});
Since your comment says you change a form variable, you could start your submit handler by checking that same form variable. If it is changed, just return true. If not, continue with the current handler.
You can use the submit() method or forms:
$(".reserveer_form").submit(function(event){
event.preventDefault();
var form = this,
$form = $(form);
$.ajax({
url: $form.attr("action"),
data: $form.serialize(),
success: function(data) {
var errors = $(".messagered", data);
if (errors.length > 0){
$(".gegevens").before(errors);
} else {
form.submit();
}
}
});
})
However, this seems to be a strange ajax request. First, you send the form (serialized, via ajax) to the server, and when the response contains no errors you send it again? The server would process it twice (and act twice, depending on your form). Also, the user does not get a message that his input is already processed - he clicks "submit", and it always takes a time until it is visibly submitted (where he even could change some input).