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

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.
}
});

Related

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.

JavaScript Form Validation Query

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

form within AJAX jQuery toggle, submits at parent onClick not from submit button

Basically mysimplewebform.php form submits when the toggle is clicked, as opposed to after the form is loaded, used by user and SUBMITTED via submit button at form. Obviously I need to have form operate functionally; user fills it out, and clicks submit. I simply used AJAX to bring in the form on the template page. Now everytime toggle button is clicked 'Form is submitted with empty values' and then appears in the toggle. Making it pretty useless at this point, I have been struggling with this forever. I think this is a matter of toggling the data: below --
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(), // This was a recent suggestion
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
Branched out from: How to send external form POST data through AJAX
Ok, so you want to display an html form when a user clicks a button? In that case you can use the simplified jquery load method:
$('#yourbutton').click(function(){
$('#somediv').load('/mysimplewebform.php');
});
I know this doesnt handle your toggle requirement, but i dont think that is where you are having issues.
Now onto the php. I dont know exactly what should be in mysimplewebform so heres an example
if(isset($_POST['fname'])){
//we have a post request, lets process it
echo 'hello'.$_POST['fname'];
}?>
<form action="absolute/path/to/mysimplewebform.php" method="post" id="mysimplewebform">
<input type="text" name="fname" placeholder="Enter Name">
<input type="submit" value="submit">
</form>
Notice the action is an absolute path to the file, because a relative path will be wrong if the form is loaded into another page via ajax.
Now when this form is submitted, the browser will be redirected to mysimplewebform.php.
I expect you want to stay on the same page, in which case you could submit the form via ajax:
$('#mysimplewebform').submit(function(ev){
ev.preventDefault();//stop normal redirecting submit
$.post( $(this).attr('action'), $(this).serialize(), function(data){
$('#somediv').html(data)
});
This replaces the whole form in the dom with the output, so the hello message would be displayed.
All of the above is an attempt to help you understand where you have been going wrong in your attempts. It is not the best solution to your overall problem - i would separate the html form and processing into seperate files for a start, but it should be familiar to you.

Redirect to any page and submit form details

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

Getting some problem with apply event to dynamic added form in Jquery

I am loading the form in dialog box via jQuery
The code is like
<form class ="form1" action="" method="post" enctype="multipart/form-data" >
...
</form>
I am using jQuery form plugin to submit form like this
$(".form1").live('submit', function(e) {
var options = {
target: '.ajaxMessage',
beforeSubmit: showRequest,
success: showResponse,
type: 'POST'
};
alert('test');
$(this).ajaxSubmit(options);
return false;
});
Now
If i load the form directly without AJAX and then i submit the form then form gets submiited successfuly without any problem. It works 10 out of 10 times
In second case I load the form dynamically. When i click on form link then i load the form dynamically in a jquery dialog box then if i click on submit form then i can see the alert but form is not submitted. But it works sometimes but sometimes not. I would say it work 2 times out of 10.
Firebug console is also not showing any error
Is there any way i can find whats problem
Firebug will usually (I actually think not at all) won't show any errors for a ajax call, instead the error will be in the ajax request(still in firebug). Click the request and then response.
My guess is that there is a problem with the params you are sending or there is something wrong with what you a returning(i.e. you return html when ajax is expecting json, this will cause success never to be fired)
Also, try to pass an error:function(jqXHR, textStatus, errorThrown){} to the ` ajaxSubmit params and see what happens.

Categories