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.
Related
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.
}
});
I've just wrote some validation code so as to check if either of my radio buttons from my web form have been selected before they are submitted. I've just starting learning php as I want to be able to store the value of each radio button in a .csv file.
Because I have my action attribute set to trigger a php script, I get my alert box, but as soon as I click OK after pressing submit the browser goes straight to the php script (inevitably).
Is there a way I can return to my initial index.html after the alert message?
I have not actually written any php as yet, so would this go in the php script or the javascript?
Heres my code so far:
$("#submit").on("click", function() {
var radio = $("input[type=radio][name=emotion]")[0].checked;
var radio2 = $("input[type=radio][name=emotion]")[1].checked;
var radio3 = $("input[type=radio][name=emotion]")[2].checked;
if(!radio && !radio2 && !radio3) {
alert("You must select at least one word!");
}
else {
alert("Please rate the next item!")
}
});
In Jquery you should use .submit() function to validate a form.
Then to avoid to submit the form you can use the function event.preventDefault()
And if you want to go to the index you can use window.location = "yourURL"
You must use form.onsubmit().
For example, if your form's name is myForm:
document.forms['myForm'].onsubmit = function()
{
if (this.elements['emotion'].value)
{
alert("Please rate the next item!");
}
else
{
alert("You must enter at least one word!");
return false;
}
}
And after alert "Please rate the next item!" form will be send.
Actually you can use jquery $.post() , an easy solution is just to post your php page without leaving index page.
http://api.jquery.com/jquery.post/
$.post( "yourpage.php" );
You probably have the input type of the submit button as submit? Set this to button, so the action doesn't take place and only jQuery is executed.
But then you have to submit the form by jQuery when validation was successful:
document.myFormId.submit();
I'm looking to submit form details using method="POST" to an external URL, then redirect the user to a 'Thank you' page after successfully completing the form.
My sample HTML/Javascript is as follows, however the page is not redirecting to Google.com as intended. Any help on fixing this would be much appreciated!
HTML:
<form action="externalURLhere" method="post" name="theForm"
id="theForm" style="margin-bottom:0px;padding:2px;background-color:#e0e0e0;" onSubmit="return
MM_validateForm(); return redirect();">
JavaScript:
function MM_validateForm() {
if ( !jQuery('#theForm #FirstName').val() ) {
alert('Please input your first name.');
jQuery('#theForm #FirstName').focus();
return false;
}
if ( !jQuery('#theForm #LastName').val() ) {
alert('Please input your last name.');
jQuery('#theForm #LastName').focus();
return false;
}
if ( !jQuery('#theForm #daytimephone').val() ) {
alert('Please input your phone number.');
jQuery('#theForm #daytimephone').focus();
return false;
}
if ( !jQuery('#theForm #Email').val() ) {
alert('Please input your email.');
jQuery('#theForm #Email').focus();
return false;
}
if ( !jQuery('#theForm #BID').val() ) {
alert('Please select your preferred campus.');
jQuery('#theForm #BID').focus();
return false;
}
if ( !jQuery('#theForm #programs').val() ) {
alert('Please select your preferred program.');
jQuery('#theForm #programs').focus();
return false;
}
if ( !jQuery('#theForm #How_Heard').val() ) {
alert('Please select how you heard about us.');
jQuery('#theForm #How_Heard').focus();
return false;
}
return true;
}
// ]]></script>
<script type="text/javascript">
function redirect() {
window.location = "www.google.com";
return false;
}
</script>
When the user clicks the submit button, onsubmit event occures, and, depending on the return value of the function binded to the event, the form submits (return true) or does not submit (return false);
The function may be binded to the event using HTML:
<form onSubmit="if(/*some validation here*/){return true;} else {return
false;}"></form>
or in javascript script itself:
form1.onsubmit=function(){if(/*some validation here*/){return true;}
else {return false;}}
Generally, it does not matter;
You know, the function's body is executed until the "return" occures. Then it immediatly stops and the return value is passed to the function invoker. So, what you have wrote in the onSubmit="" HTML tag attribute is the equivalent of the following JS code:
form1.onsubmit=function(){
testPassed=validate();
return testPassed;
someValueRedirectFunctionReturns=redirect();
return someValueRedirectFunctionReturns;
}
So, you can see, that no matter if the form data test is passed or not, because your validate() function's return value (true if form is okay and false if user has entered bad data) is immediatly then returned in the event function. So, your redirect() function cannot occur, because the onsubmit event handler function is stopped and the value is returned;
To make this work, you should modify the code:
form1.onsubmit=function(){
if(!validate())
return false; //test failed, form is not passed, no need to redirect to "thank you page".
else
redirect();
}
So, the redirect function will be called if the form validation test is passed. Right here we ran in an another problem.
The only way, if the onsubmit event handler function is defined, to submit the form is to return true; -- return from the function, means stop it and proceed executing from the where it was called. When you change the window.location propterty of the page in the function, redirection occurs immediatly, so the function even do not return; -- JavaScript execution immediatly interrupts, and the new page starts loading -- of course, no data can be passed via form submition;
So, you have to
Submit form (if the data is valid) -- return true;
Somehow redirect (this means, to continue execute your JS code at another page) from the page where the form is submitted.
And... that is not possible.
You can't continue executing the JS code after the form is sent because:
The event handler function has returned. That means it is stopped.
The form is sent, and an another page is now loading. The JS code of the previous page is lost, and cannot be executed anymore.
This means, that you can't affect the behaviour of the page that you are loading (in synchronous mode) from the page, that has started the loading.
And you can't make the new page redirect to the page you want ("thank you" one).
Usual form sending is just loading a new page with additional parameters. E. g. you can't modify the page that a link on your page is following to;
Anyway, there are still several ways to acheive what you want:
If YOU own the page, where the form is submitted, you may just receive the data of the form and immediatly send the redirection header. E. g., via PHP on the server side.If the page IS NOT YOURS (you can't modify neither the server, nor the page, nor anything on the server side), then you have to work with the form in slightly different way(s):Use frames or floating frames, either loading the data into the frame(s) by the javascript code itself, or by loading another page (from the same server on which the form page is located), that you have permission to modify, and modify it. E. g.:In one frame, make a form where the user actually enters data;In another frame, make another form which contains the same fields that the first does, but hidden ones;Do not submit the first form, but pass the data from to the second form, and submit() the second one;Redirect the first frame (or the whole page) to the "thank you" page;The first frame may be even hidden (CSS: display:none) -- that won't affect the functionality.Use AJAX. That is a special technology of making HTTP request (submitting form!) from the javascript code without reloading the actual page. There may be some problems, if you try to send data to the externalURLHere page, if it is not yours. If so, you may create a "router" page on your server, which will receive the data sent by the form and route it to the target, externalURLHere page. Then you may even...Don't use AJAX. Just make the router page (when I say "page", I mostly mean a PHPscript, or another cgi technology), which will also display the "Thank you" HTML document.And so on...
I've tryied to make as complete answer, as possible, I hope it has helped.
P. S. Sorry for my English.
P. P. S. My first answer on Stack Overflow -- I may be doing something wrong, sorry.
It's tough to pin down the exact reason why it isn't working without your full code and more specific requirements.
For instance, if you are submitting to a php file, you can do the redirect in that external php file using:
header('Location: http://www.example.com/');
If you are simply submitting to another html file, you could use Ajax: How to redirect using AJAX?
Try to add protocol
window.location = "http://google.com";
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.
I'm designing a rather long form that will auto-save every couple minutes (i.e., using Ajax, the form data will be inserted or updated into the MySQL database). However, if the user decides to exit the page before submitting the form, I want to make sure I delete the row that was inserted into the database. This is easily do-able if the user simply clicks another link or the form's Cancel button. But I'm concerned about what happens when the user: 1) closes the page, 2) reloads the page, or 3) hits the browser's back (or forward) button. I know how to use the unload event to create a confirmation dialog asking the user to confirm they want to leave the page. But what I don't know is how to make an Ajax call (to delete that row from the database) if the user clicks OK ("Press OK to Continue"). Is there any way to call a function if a user clicks the OK button during the unload event?
window.onbeforeunload = function() {
if ($('#changes_made').val() == 'yes') //if user (partially) filled out the form
{
return "Are you sure?"
if (/*user clicks OK */) //What should the if statement evaluate here?
{
//make Ajax call
}
}
};
$(document).ready(function() {
$(':input',document.myForm).bind("change", function() {
setConfirmUnload(true);
}); // Prevent accidental navigation away
});
function setConfirmUnload(on) {
// To avoid IE7 and prior jQuery version issues
// we are directly using window.onbeforeunload event
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
if(Confirm('You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.')) {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
}
Make sure you have upgraded version of jQuery. jQuery version 1.3.2 had a bug:
Ticket #4418: beforeunload doenst work correctly
Or use native function:
window.onbeforeunload = function() {....}