Submit form (and disable button) in dynamically added content - javascript

I have a one-page design, where I set a main div to hold and show the current "page" content (with jquery)
Then I have this in a js file:
$(document).on("submit", "#kontaktform", function(){
$theform = $(this);
$.ajax({
url: "kontakt_val.php",
type: "POST",
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (!data OR data=="ok") {
// AJAX ERROR OR OK: Continue to php validation
$("input[type=submit]",$theform).attr("disabled", "disabled");
$theform.unbind("submit").submit();
} else {
$("#jserrors").html('<p class="error">' + data + '</p>');
$("#jserrors").slideDown(150);
}
},
error: function(e) {
// AJAX ERROR: continue to php validation
$("input[type=submit]", $theform).attr("disabled", "disabled");
$theform.unbind("submit").submit();
}
});
return false;
});
$theform.unbind("submit").submit(); does not seem to submit the form
I'm thinking, it's because the form is in content that is dynamically added with js/jquery
How to fix this?

This seems to work:
document.forms["kontaktform"].submit();
Don't know how to do it Jquery style though

Related

Why doesn't my form work on mobile devices?

I have a form downloaded from http://reusableforms.com/ that works great on desktop. But the submit button changes to "sending ..." and gets stuck on mobile devices. An error message doesn't display and the page just stops working. What would cause this problem? I am putting my javascript code below. Here is the site for reference: http://jasminew.xyz/flash
$(function()
{
$.ajaxSetup({ cache: false }); // or iPhones don't get fresh data
function after_form_submitted(data)
{
if(data.result == 'success')
{
$('#carouselExampleIndicators').hide();
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else
{
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors,function(key,val)
{
$('#error_message
ul').append('<li>'+key+':'+val+'</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function()
{
$btn = $(this);
label = $btn.prop('orig_label');
if(label)
{
$btn.prop('type','submit' );
$btn.text(label);
$btn.prop('orig_label','');
}
});
}//else
}
$('#reused_form').submit(function(e)
{
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function()
{
$btn = $(this);
$btn.prop('type','button' );
$btn.prop('orig_label',$btn.text());
$btn.text('Sending ...');
});
var formdata = new FormData(this);
$.ajax({
type: "POST",
url: 'handler.php',
data: formdata,
success: after_form_submitted,
dataType: 'json' ,
processData: false,
contentType: false,
cache: false,
});
});
});
EDIT
I have opened remote Safari dev tools and the XHR Post is timing out. I'm not sure what that means.
EDIT
Okay, the problem is that the form stops working if the two upload fields in the form aren't used on iOS. Does anyone know a workaround?
I reviewed your code and would suggest some minor updates:
$(function() {
$.ajaxSetup({
cache: false
}); // or iPhones don't get fresh data
function after_form_submitted(data) {
if (data.result == 'success') {
$('#carouselExampleIndicators').hide();
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
} else {
$('#error_message').append('<ul></ul>');
$.each(data.errors, function(key, val) {
$("<li>").html(key + ": " + val).appendTo($('#error_message ul'));
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function() {
var $btn = $(this);
var label = $btn.data('orig-label');
if (label) {
$btn.prop('type', 'submit');
$btn.text(label);
$btn.data('orig-label', null);
}
});
}
}
$('#reused_form').submit(function(e) {
e.preventDefault();
var $form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function() {
var $btn = $(this);
$btn.prop('type', 'button');
$btn.data('orig-label', $btn.text());
$btn.text('Sending ...');
});
var formdata = new FormData($form[0]);
$.ajax({
type: "POST",
url: 'handler.php',
data: formdata,
success: after_form_submitted,
dataType: 'json',
processData: false,
contentType: false,
cache: false,
});
});
});
I see nothing that is "wrong", just some syntax cleanup. Also this was sort of ambiguous in the creation of FormData, so I switched to a more specific element: $form[0].
I adjusted a few other things to be more jQuery like. All functions the same.
Also, make sure that Ajax URL path is correct. You have:
url: 'handler.php'
Make sure that your can browse to this directly. If the path is not correct, the form will not post properly. It may be better to use a Direct URL Path instead of a relative path.
If you have access to your Web Server or PHP Logs, you can also check there to see if POSTs to your handler.php script are failing in some way. In Safari, you may want to check Network results and see if it provide more response details.
Test it, let me know if it works any better.

Clearing a form and closing the div after successful post

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

Form submitting to wrong function when changing class dynamically

I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo

Form submit Ajax using jQuery sometimes does not works

I am doing form data submit using Ajax with jQuery.
When I submit form on popup window, I refresh the parent page.
My code:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webapp/addSpeedDataAction.do",
data: $(this).serialize(),
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});
However page gets refreshed on success of callback but i can not see update on my parent page. Sometimes I can see updates and sometimes not. What is the issue? I also need to know how I can write it in native javascript and submit form using ajax javascript.
Maybe your getting this error due the fact that javascript is async and your code will proceed even when you have yet no response from the request.
Try this:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webfdms/addSpeedDataAction.do",
data: $(this).serialize(),
async: false, // This will only proceed after getting the response from the ajax request.
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});

Only send post/get if form values has changed

I want to prevent multiple ajax calls (user holds enter key down or multi presses submit or other)
I'm thinking, the best way is to use a var with the previous form post values and compare them at each click/submit.. Is it the same? : Then do nothing
But I don't know how to go about it
Here is my javascript/jquery:
$('form').submit(function() {
$theform = $(this);
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
Not very creative with naming vars here:
var serial_token = '';
$('form').submit(function() {
$theform = $(this);
if ($(this).serialize() === serial_token) {
console.log('multiple ajax call detected');
return false;
}
else {
serial_token = $(this).serialize();
}
$.ajax({
url: 'validate.php',
type: 'POST',
cache: false,
timeout: 5000,
data: $theform.serialize(),
success: function(data) {
if (data=='' || !data || data=='-' || data=='ok') {
// something went wrong (ajax/response) or everything is ok, submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
} else {
// ajax/response is ok, but user input did not validate, so don't submit
console.log('test');
$('#jserrors').html('<p class="error">' + data + '</p>');
}
},
error: function(e) {
// something went wrong (ajax), submit and continue to php validation
$('input[type=submit]',$theform).attr('disabled', 'disabled');
$theform.unbind('submit').submit();
}
});
return false;
});
You could combine this with a timeout/interval function which aborts the submit, but the code above should just compare the data in the form
If you have some kind of submit button, just add a class 'disabled' to it when you start the ajax call, and check if it is present before trying to make the call. Remove the class when the server gives a response. Something like:
...
$theform = $(this);
$button = $theform.find('input[type=submit]');
if ($button.hasClass('disabled')) {
return false;
}
$button.addClass('disabled');
$.ajax({
....
},
complete: function () {
$button.removeClass('disabled');
}
});
...

Categories