jquery tools validation re-bind after loading different content - javascript

I'm using the jquery tools validation plugin for client side form validation.
i have one javascript file which loads the function below on ready.
What i'm doing is, i load a form, when this is being validated successfully and submitted,
i load another form, and would like the function below to handle any form thats being loaded
within the if (json.success && json.next) statement block.
For some reason, when the second form is loaded, the validator is not being re-bound to the
class (.signup_form) of the new form, and the validation does not occur.
any idea how i could attach a $.live or anything to this, so it'll automatically rebind itself to whatever form gets loaded with the .signup_form class after success?
/* For clarification: json.next is the url of the next form to load */
$(".signup_form").validator({
position: 'top left',
offset: [-12, 0],
message: '<div><em/></div>' // em element is the arrow
}).submit(function(e) {
var form = $(this);
// client-side validation OK.
if(!e.isDefaultPrevented()) {
// submit with AJAX
$.post(form.attr('action'), form.serialize(), function(json) {
// everything is ok. (server returned true)
if (json.success && json.next) {
form.parent().parent().load(json.next); // Slide here
form.reset();
// server-side validation failed. use invalidate() to show errors
} else {
form.data("validator").invalidate(json);
}
}, "json");
// prevent default form submission logic
e.preventDefault();
}
});
any help is greatly appreciated.
T
Okay, i figured it out... geez its so obvious.
so all of the code above i have within a
form_listener = function() {}
block.
now all i need do do is to call the form listener after i load the new form:
.
.
// everything is ok. (server returned true)
if (json.success && json.next) {
form.parent().parent().load(json.next, function(){
form_listener();
});
.
.
sweet.

Related

Contact Form 7 : Not routing to new page

I am using Contact Form 7 and JS to load a new page upon successful form submission. However, upon the submission of the contact form, I am routed to the following url: https://example.com/#wpcf7-f95-p2-o1
My inline JS is as follows:
document.addEventListener( 'wpcf7mailsent', function( event ) {
alert("The form has been sent");
location = 'http://www.example.com/thank-you/';
}, false );
However, this redirect (to url/#wpcf7-f95-p2-o1) occurs on all browsers and devices, and the alert message never populates. There are no console errors or warnings pertaining to this script - which leads me to believe that this script is never being triggered.
Is there something that I could have done in order to prevent this function from opperating?
Try adding this code to functions.php:
add_filter('wpcf7_form_action_url', 'remove_unit_tag');
function remove_unit_tag($url){
$remove_unit_tag = explode('#',$url);
$new_url = $remove_unit_tag[0];
return $new_url;
}
this will remove the tag, also for redirecting, you can use something like this which gives more options

After validating & submitting form, reset form + change some css styles

I have a simple html contact form with validation check.
I would like to have some commands executed after a successful form submission. But the way I've set this whole thing up... I can't make it work.
HTML contact form:
<form id="mycontact_form" name="form_name" method="post" onsubmit="return validateForm();" action="https://domain.tld/cgi-bin/sendformmail.pl">
validateForm.js:
function validateForm() {
//validating input fields
if (!valid){
return false;
} else {
if(condition1 == true)
{
document.form_name.submit(); return;
}
else {
// doing stuff to form content
document.form_name.submit(); return;
}
}
}
When the submit button is pressed, the form is validated and will be submitted to the perl script sendformmail.pl which return a HTML Status 204 so the user stays on this page and is not redirected (that's the only way I got this part to work).
Now what I would like to have after a successful submission is:
clear/reset the form and
some minor UI stuff: change background of 2 elements + placeholder/inner text of 2 input fields for thank you message.
But for example if I put document.form_name.reset() after the document.form_name.submit(), it's too fast. It resets the form before submissions. I also tried to call another (independent) function after the validateForm() in the onsubmit but that seems to be wrong (well, at least it's not working).
So I guess I need to put these 2 things (reset + CSS changes) in a separate function and call it after a successful form submission.
But how, where and when?
I'm very interested to learn a simple yet effective solution. (but jQuery is also available)
Thank you for your help.
If your email script is on the same domain as your contact form, try submitting it via ajax. Here's a simple jQuery example, which would be in your onsubmit handler:
if (valid) {
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
})
.done(function() { // this happens after the form submit
$("#mycontact_form")[0].reset();
});
}
return false; // don't submit the form again non-ajax!
Otherwise, if on different domains, try setting the target of your form to the id of a hidden iframe on your page. Since this is cross-domain, you have no real way of knowing the result of the form submit due to the same origin policy. You can simply hope for the best and reset the form after X number of seconds:
if (valid) {
$("#mycontact_form").submit();
// clear form 3 seconds after submit
window.setTimeout(function() {
$("#mycontact_form")[0].reset();
}, 3000);
}
Both of these approaches keep the user on the same page without a refresh.
I ended up using beforeSend with ajax instead of done. And instead of resetting the form I chose to clear the value of the input fields/textarea (there are only 3). I also included the preferred 'post-submission' style of the input fields/textarea in beforeSend to leave nothing to chance.
Anyway, thank you for helping me & pointing me in the ajax direction.
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
beforeSend : function (){
// clear value of input fields/textarea & disable them
// use placeholders for "Thank you." etc.
}
});

Trouble with ajax script using onClick to submit form

I have several forms on a page that submit values from radio buttons using jquery/ajax. All works fine when a Submit button is used, but I would like to eliminate the Submit button. I tried using onClick to submit. However, trying it this way causes the forms to get submitted prior to the processing script picking them up. I would very much appreciate advice (and example if possible). Thank you, Brian
Script:
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
var formData = $(this).serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
if (data.success) {
// success.
// hide form container
$("#"+data.message).hide();
$("#"+data.message+"hr").hide();
}
// log data to the console so we can see
//console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
Form:
<method="post" action="process.php" enctype="multipart/form-data">
<input type="radio" name="answer" value="yes" onClick="onClick="this.form.submit()">
Your syntax for onclick is wrong, but putting onclick attributes on elements is an outdated way of doing things in any case.
You probably want to handle the change event rather than click, since the selection of the radiobutton happens after the click, so if you submit the form right away the radiobutton might not be selected yet (I'm not sure, I'd have to experiment, but change is probably more foolproof).
$(document).ready(function() {
$('input[type=radio]').change(function(event) {
//the rest of your code goes here
//you don't need event.preventDefault() anymore
});
});
Edit: $(this) won't refer to the form anymore of course, just replacing it with $('form') should do the trick.

$(id).submit() not triggering submission of form

I have a form that needs to do two things when the user clicks the submission button. The first is send an e-mail to me, and the second is send the user to PayPal. I have set it up so it first makes an Ajax call to another page, and that page sends the e-mail. Once that page returns a success, it calls a function to trigger the submission of the form.
I've put in the form with a standard button, rather than a submission button, and an onclick even to detect when it's clicked. Everything works great up until I try to submit the form after the Ajax call, at which point the form isn't submitted. Here's my javascript:
$('#submit-btn').on('click', function() {
var err = false;
$('input, textarea', '#booking-form').each(function(index, element) {
if($(this).is('[required]') && $(this).val() < 2) {
alert('Please enter your ' + $(this).prop('placeholder').toLowerCase() + ' before continuing.');
$(this).focus();
err = true;
return false;
}
});
if(err) {
return false;
}
if($('#date').val() == 0) {
alert('You must choose a date before booking');
return false;
}
ShowLoadingScreen();
var data = {
'name': $('#name').val(),
'address': $('#address').val(),
'tel': $('#tel').val(),
'email': $('#email').val(),
'course': $('#course').find('option:selected').text(),
'location': $('#location').find('option:selected').text(),
'date': $('#date').find('option:selected').text()
};
AjaxHandler('book-course.php', data, "POST", true);
//AjaxHandler sends the data off to book-courses.php, which then returns a call to BookingSuccess().
//This is working fine as evidenced by the console.log line showing in the console.
});
function BookingSuccess() {
$('#booking-form').submit();
console.log('Booking success called...');
}
AjaxHandler is a custom function that calls the page, and then handles certain responses, including calling functions. BookingSuccess is being called, as Booking success called... is being output in the console. The form however just isn't being submitted.
I have created a jsFiddle of the issues here.
What I've tried
So far I've tried the following:
Skipping around the Ajax - no effect
Submitting the form directly using a button, ignoring the need for Ajax - the form works fine.
Deleted all HTML except for the form - no effect
Tried submitting the form at the top of the #submit-btn click event - no effect
Place a return true function inside the $('#booking-form').submit() - no effect
Using the longer version of jQuery's trigger $('#booking-form').trigger('submit') - no effect.
Putting a console.log event in the forms onsubmit="" to see if the form is being triggered - Works on the fiddle, but not the website.
I'm at a loss as to why this form will not submit. Nothing should be stopping it. We're getting to and passing that line. I have placed a break in FireBug and stepped in, and we get to that function fine. It just doesn't do its job.
How can I get this form to submit properly as it should?
Upon further inspection (and some dead ends and red herrings in the chat), it looks like the page has two elements with the same ID. Change one or the other, and you're golden.

How to excecute Javascript after failed form validation

I am using ASP.NET 3.5, and the jquery.hint.js plugin. It works great, with one small problem. I have various ASP.NET validators on the page and when the page fails to validate, client-side, all of the textboxes that contained hint text are now blank. This is confusing for the end-user because their are no field labels. To see the hint text, they must click in and out of the field and it re-populates.
Not sure if it makes a difference, but these fields are wrapped in an ASP.NET AJAX UpdatePanel. The reason for the update panel is to do some asynchronous calls for dynamic field updates like auto-populating the state dropdown based on what country you choose. The form is submitted via postback.
I need a way to call the hint javascript against these fields after the validation fails on the client side. How can I do this?
Here is an example of the client side code that executes the hint plugin against the various fields on the page:
<script type="text/javascript">
$(document).ready(function () {
// Add handler function to UpdatePanel's events
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
PageLoad();
});
function PageLoad() {
RetainState();
}
// This function handles the UpdatePanels' EndRequest event.
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
RetainState();
}
else { // there was an error
alert("There was an error" + args.get_error().message);
}
}
function RetainState() {
// Add hint to textboxes.
$(":text").hint();
$("textarea").hint();
}
</script>
One last thing: I thought I had already fixed this problem by adding the following code to the Page_Load method in the code behind, but if it was working before, it is not now:
// This will call some javascript after a form validation fails
// and keep the hint text in the form fields.
if (!Page.ClientScript.IsOnSubmitStatementRegistered("KeepState"))
{
string script = "RetainState()";
Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "KeepState", script);
}
Thanks,
Tod

Categories