Hide the RSForm form when submitted - javascript

I have this AJAX code which successfully shows the "loading.." message when submitted in RSForm.
I want to hide the form when the user clicks the submit button. How should I go about editing in this javascript?
<script>
jQuery(function($){
$(document).ready(function() {
var options = {
beforeSubmit: showRequest,
success: showResponseAll
};
// bind to the form's submit event
$('#userForm').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.my-message').html("Loading....");
return true;
}
// post-submit callback
function showResponseAll(responseText, statusText, xhr, $form) {
var $response = $(responseText);
var comon = $response;
var dane = comon.find('.message-load')
$('.my-message').html(dane);
}
});
</script>
<form method="post" id="userForm" action="URL"><div class="my-message"></div>
<div class="message-load"><div id="rsform_error_3" style="display: none;"><p class="formRed">Please complete all required fields!</p></div></div>
<fieldset class="form-horizontal formContainer" id="rsform_3_page_0">
<div class="form-group rsform-block rsform-block-email">
<div class="col-xs-12 formControls">
<input type="text" value="" size="20" placeholder="you#email.com" name="form[Email]" id="Email" class="rsform-input-box form-control rsform-input-box">
<span class="formValidation"><span id="component27" class="formNoError">Please let us know your email address.</span></span>
</div>
<div class="col-xs-12">
<button type="submit" name="form[Join Newsletter]" id="Join Newsletter" class="rsform-submit-button btn btn-primary">Join Newsletter</button>
</div>
</div>
</fieldset>
<input type="hidden" name="form[formId]" value="3">
</form>
I believe we must add something to pre-submit callback but I don't know how. I want to hide the form and show them a "thank you" message when somebody clicks the submit button

Not able to make out when you say RSForm. Presuming you are referring to same userForm
$('#userForm').submit(function(event) {
//since making ajax call you have to prevent the default behavior that is submit
event.preventDefault();
$('#userForm').hide();
$(this).ajaxSubmit(options);
return false;
});
});
Note:This id="Join Newsletter" may not be a valid value for id attribute.
You can check this LINK to know more about valid values.

You can use .ajaxStart() method:
$(document).ajaxStart(function(){
$('#userForm').hide();
$('#userForm').find('.my-message').html("Thank You!!!");
});
Or add the two lines in these functions:
// pre-submit callback
function showRequest(formData, jqForm, options) {
$('.my-message').html("Loading....");
$('#userForm').hide(); // <------------hide it here
return true;
}
// post-submit callback
function showResponseAll(responseText, statusText, xhr, $form) {
var $response = $(responseText);
var comon = $response;
var dane = comon.find('.message-load')
$('.my-message').html(dane); // <----i suppose this is Thank you message.
}

Related

jQuery : How to do validation in jquery before submit the form?

I have a form bootstrap form like below
<form id="loginForm" method="post" action="" role="form" class="ajax">
<div class="form-group">
<label for="userName"></label>
<input type="text" class="form-control" id="usrName">
</div>
<div class="form-group">
<label for="passWrd"></label>
<input type="password" class="form-control" id="passWrd">
</div>
<div class="form-group">
<button class="btn btn-default" type="button" id="loginButton">Login</button>
</div>
I am doing form validation in my jquery as below. How do I call submit() method in my code? i.e how do I make ajax call to submit the form content after validation in the jQuery.
$(document).ready(function() {
function validateInput(id) {
if($("#"+id).val()==null || $("#"+id).val()=="") {
var div=$("#"+id).closest("div");
div.addClass("has-error");
return false;
} else {
var div=$("#"+id).closest("div");
div.removeClass("has-error");
div.addClass("has-success");
return false;
}
}
$(#loginButton).click(function() {
enter code here
if(!validateInput("userName"))
{
return false;
}
if(!validateInput("passWrd"))
{
return false;
}
});
});
How do i call $.ajax after i complete the validation in my above code?
P.S : I am not supposed to use any jquery plugin for the validation.
$('#loginForm').submit() will submit the form.
Try this:
$(document).ready(function() {
function validateInput(id) {
var element = $("#"+id);
var success = false;
if (element.val() == null || element.val().trim() == "") {
element.closest("div").addClass("has-error");
} else {
var div = element .closest("div");
div.removeClass("has-error");
div.addClass("has-success");
success = true;
}
return success;
}
$(#loginButton).click(function() {
if (validateInput("usrName")) {
$('#loginForm').submit()
}
});
});
<div ng-class="{ 'form-group has-error has-feedback' : datos.campo.$invalid && !datos.campo.$pristine, 'form-group has-success has-feedback' : datos.campo.$valid}">
<label class="control-label" for="campo">Modelo</label>
<input ng-model="data.campo" name="campo" type="text" class="form-control" id="campo" required>
<span ng-class="{'glyphicon glyphicon-remove form-control-feedback':datos.campo.$invalid && !datos.campo.$pristine, 'glyphicon glyphicon-ok form-control-feedback':datos.campo.$valid}"></span>
<span ng-show="datos.campo.$invalid && !datos.campo.$pristine" class="col-md-8 center badge badge-danger">Incorrecto</span>
</div>
Con Angular JS es mas facil validar campos, Checa este link
This code will check EVERY input field.
$(#loginButton).click(function() {
if (!$.trim($("input").val()) { //check ALL input fields, see if they have valid (non-falsy) values
alert("some input needs fixin'!");
} else {
submit(); //since you mentioned this in your post
$.ajax({});//or make an ajax call, or put it inside of a function and call that, the possibilities are endless..
}
});
Although this can be done in several ways, using your example, I can see that you are already returning false on validation failure. Return true from the end of your validateInput() method.
function validateInput(item) {
var div=item.closest("div");
if(item.val()==null || item.val()=="") {
div.addClass("has-error");
return false;
} else {
div.removeClass("has-error");
div.addClass("has-success");
return true;
}
}
Then, in the click event handler, check the returned value and call the form.submit()
$('#loginButton').click(function() {
var isValid = true;
$('.form-control').each(function(){
isValid &= validateInput($(this));
});
if (isValid)
{
var data = $('#loginForm').serialize();
$.ajax({
url: 'your endpoint',
type: 'POST',
data: data
});
}
});
to submit the form.
Here's a working Plunkr.
You could use this plugin. This is the best and easiest to use plugin I have found for validating a form.

jquery email signup form trying to hide form after submit

I am trying to use a simple jquery/php newsletter script. The script works fine. As I enter name and email and hit the submit button, it saves data into a .txt file, and display a success message along with the form. Now, I would like to modify the script. I do not want the form to be seen as I hit the submit, instead it should show the success message only "Thank you." Being very novice to javascript, I have so far figured out that I need to "fadeOut" the form after clicking the submit button.
I think the code might be look like
$("#submit").on("click", function(e) {
e.stopImmediatePropagation();
$("#signup").fadeOut(280, function() {
// callback method to display new text
// setup other codes here to store the e-mail address
$(this).after('<p id="success">Thank you</p>');
});
});
I have tried to integrate this code, but due to my limited JS experience I cannot do it successfully.
Here is my original jquery script
var error_1 = "Please enter your valid email address";
var error_2 = "Please enter your name";
var thankyou = "Thank you";
function trim(str) {
str = str.replace(/^\s*$/, '');
return str;
}
function $Npro(field) {
var element = document.getElementById(field);
return element;
return false;
}
function emailvalidation(field, errorMessage) {
var goodEmail = field.value.match(/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/);
apos = field.value.indexOf("#");
dotpos = field.value.lastIndexOf(".");
lastpos = field.value.length - 1;
tldLen = lastpos - dotpos;
dmLen = dotpos - apos - 1;
var badEmail = (tldLen < 2 || dmLen < 2 || apos < 1);
if (!goodEmail || badEmail) {
$Npro("Error").innerHTML = errorMessage;
$Npro("Error").style.display = "inline";
field.focus();
field.select();
return false;
} else {
return true;
}
}
function emptyvalidation(entered, errorMessage) {
$Npro("Error").innerHTML = "";
with(entered) {
if (trim(value) == null || trim(value) == "") { /*alert(errorMessage);*/
$Npro("Error").innerHTML = errorMessage;
$Npro("Error").style.display = "inline";
return false;
} else {
return true;
}
} //with
} //emptyvalidation
function signup(thisform) {
with(thisform) {
if (emailvalidation(email, error_1) == false) {
email.focus();
return false;
};
if (emptyvalidation(name, error_2) == false) {
name.focus();
return false;
};
}
$("#submit, #myResponse").hide(); // Hide the buttom and the message
$("#loading").show(); // show the loading image.
params = $("#subform").serialize();
$.post("optIn.php", params, function(response) {
//alert(response); //may need to activate this line for debugging.
$("#loading").hide();
$("#myResponse").html(thankyou); //Writes the "Thank you" message that comes from optIn.php and styles it.
$('#myResponse').css({
display: 'inline',
color: 'green'
})
$("#submit").show();
})
return false;
}
Here is the html markup
<form onSubmit="return signup(this);return false;" method="post" name="subform" id="subform" action="
<?php echo optIn.php ?>">
<div>
<span style="FONT-FAMILY: Arial; FONT-SIZE: 12pt; font-weight:bold;">Subscribe to our newsletter</span>
</div>
<div style="margin-top:20px">
<div>
<label style="display: inline-block;width:135px">Email:</label>
<input type="text" id="email" name="email" value="">
</div>
<div>
<label style="display: inline-block;width:135px">Name:</label>
<input type="text" name="name" id="name" value="">
</div>
<div>
<div style="display:inline-block;width:135px;"> </div>
<input type="submit" id="submit" name="submit" value="Sign up">
</div>
<div style="width:100%">
<span id="Error" style="color:red;display:none;"></span>
</div>
<div id="myResponse" style="DISPLAY:none;"></div>
<div id="loading" style="display:none;">
<img src="wait.gif" alt="">
</div>
</div>
</form>
Here is my php code:
<?php
//ini_set('display_errors', 0);
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
$email = trim(htmlspecialchars($_REQUEST["email"]));
$name = trim(htmlspecialchars($_REQUEST["name"]));
$pfileName = "mails.txt";
$MyFile = fopen($pfileName, "a");
$nline="\"".$email."\"" ."," ."\"".$name."\"" ."\r\n";
fwrite($MyFile, $nline);
fclose($MyFile);
die;
?>
Try providing a .delay() so that the fadeOut() function has finished before attempting to display the success message:
$("#submit").on("click", function(e) {
e.stopImmediatePropagation();
$("#signup").delay(500).fadeOut(280, function() {
$(this).after('<p id="success">Thank you</p>');
});
});
If I understand you correctly you want the user to submit the information via your html form. Then you want the form to go away after you hit the submit button.
From reading the JQuery method you have tried I found one mistake that is preventing your form from fading out. You were using the wrong id for your form in your JQuery code(it should be subform according to your html). Note that I removed your PHP code so that I could create an example in jsfiddle for you. My sample posts to google.com to prevent your from getting an error page displayed in the results sections.
jsfiddle: fade out form on submission
$("#submit").on("click", function(e) {
//changed from e.stopImmediatePropogation()
e.preventDefault();
//#subform is the actual id of your form, you were using signup
$("#subform").fadeOut(280, function() {
// callback method to display new text
// setup other codes here to store the e-mail address
$(this).after('<p id="success">Thank you</p>');
});
});

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

AJAX POST incorrectly works like GET

I am trying to post contact page data to my view, but it stopped working when I included if else statements.
Here is my script:
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
}else
{
return true;
}
}
</script>
And here is my form:
<form class="contact-form">
{% csrf_token %}
<p class="input-block">
<label for="contact-name"><strong>Name</strong> (required)</label>
<input type="text" name="name" value="" id="contact-name" required>
</p>
<p class="input-block">
<label for="contact-email"><strong>Email</strong> (required)</label>
<input type="email" name="email" value="" id="contact-email" required>
</p>
<p class="input-block">
<label for="contact-subject"><strong>Subject</strong></label>
<input type="text" name="subject" value="" id="contact-subject">
</p>
<p class="textarea-block">
<label for="contact-message"><strong>Your Message</strong> (required)</label>
<textarea name="message" id="contact-message" cols="88" rows="6" required></textarea>
</p>
<div class="hidden">
<label for="contact-spam-check">Do not fill out this field:</label>
<input name="spam-check" type="text" value="" id="contact-spam-check" />
</div>
<input type="submit" value="Submit" onclick="javascript:Submit();">
<div class="clear"></div>
</form>
Without the if else it was working fine but now all pages are reloading with all form data as query parameters. How can I correct this?
First you need to prevent the default action if you are trying to do AJAX.
Since, I see you are already using jQuery. I recommend adding the following to the top of your <script>:
$("#contact-form").submit(function(e){
e.preventDefault();
Submit();
});
Obviously, you won't need this anymore..
onclick="javascript:Submit();"
Now run this code in any sort of javascript debugger (Chrome and Safari both have good ones) and you should be good!
Try this please..i hope it works...
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".contact-form").submit(function(e){
e.preventDefault();
Submit();
});
});
</script>
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
}
}
You need to return a false from your Submit() function. Also, call the function from the form tag using onsubmit handle.
<form class="contact-form" onsubmit="Submit();">
and in Submit() function:
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
} else {
return true;
}
Do not use javascript: in an onxxx event handler. javascript: is a protocol specifier that goes on a URL, but the onclick handler expects raw javascript, not a URL.
You need to return false from the onclick to prevent the default action of submitting the form. I assume you do want to prevent the default and use AJAX instead?

Capturing a form submit with jquery and .submit

I'm attempting to use jQuery to capture a submit event and then send the form elements formatted as JSON to a PHP page.
I'm having issues capturing the submit though, I started with a .click() event but moved to the .submit() one instead.
I now have the following trimmed down code.
HTML
<form method="POST" id="login_form">
<label>Username:</label>
<input type="text" name="username" id="username"/>
<label>Password:</label>
<input type="password" name="password" id="password"/>
<input type="submit" value="Submit" name="submit" class="submit" id="submit" />
</form>
Javascript
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
});
Wrap the code in document ready and prevent the default submit action:
$(function() { //shorthand document.ready function
$('#login_form').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
var data = $("#login_form :input").serializeArray();
console.log(data); //use the console for debugging, F12 in Chrome, not alerts
});
});
try this:
Use ´return false´ for to cut the flow of the event:
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
Edit
corroborate if the form element with the 'length' of jQuery:
alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
OR:
it waits for the DOM is ready:
jQuery(function() {
alert($('#login_form').length) // if is == 0, not found form
$('#login_form').submit(function() {
var data = $("#login_form :input").serializeArray();
alert('Handler for .submit() called.');
return false; // <- cancel event
});
});
Do you put your code inside the event "ready" the document or after the DOM is ready?
Just replace the form.submit function with your own implementation:
var form = document.getElementById('form');
var formSubmit = form.submit; //save reference to original submit function
form.onsubmit = function(e)
{
formHandler();
return false;
};
var formHandler = form.submit = function()
{
alert('hi there');
formSubmit(); //optionally submit the form
};
Just a tip:
Remember to put the code detection on document.ready, otherwise it might not work. That was my case.
$(document).ready(function () {
var form = $('#login_form')[0];
form.onsubmit = function(e){
var data = $("#login_form :input").serializeArray();
console.log(data);
$.ajax({
url: "the url to post",
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
},
error: function(xhrRequest, status, error) {
alert(JSON.stringify(xhrRequest));
}
});
return false;
}
});
<!DOCTYPE html>
<html>
<head>
<title>Capturing sumit action</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" id="login_form">
<label>Username:</label>
<input type="text" name="username" id="username"/>
<label>Password:</label>
<input type="password" name="password" id="password"/>
<input type="submit" value="Submit" name="submit" class="submit" id="submit" />
</form>
</body>
</html>

Categories

Resources