Form submission js/jquery staying on same page - javascript

I'm trying to submit a form inside a CMS page and don't want a new page to load after processing the php mail script. Instead I need to display a single line success message (not an alert pop up box) without reloading the page or going to a different page.
Here's the code I have and my understanding is that the event.preventDefault should allow to stay on same page and $("#contactResponse").html(data); should put the success message on the same page.
This is my div tag above the form which is supposed to receive the success message (I've tried putting it after my form too):
<div id="contactResponse"></div>
This is my form tag:
Edit: Including my form code as well: (The div class stuff is from a custom css that someone else has done)
<form id="contactForm" name="contactForm" method="post" action="/myemail.php">
<div class="form-group"><input class="form-control" name="email" type="email" placeholder="Email Address" /></div>
</div>
<div class="col-sm-4">
<div class="form-group"><input class="form-control" name="question" type="text" placeholder="What is your question?" /></div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" type="submit" value="Request Information"></div>
</form>
This is the script above my form and div tag:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$("#contactForm").submit(function(event) {
event.preventDefault();
var $form = $(this),
$submit = $form.find('button[type="submit"]'),
email_value = $form.find('input[name="email"]').val(),
message_value = $form.find('input[name="question"]').val(),
url = $form.attr('action');
var posting = $.post(url, {
email: email_value,
question: message_value
});
posting.done(function(data) {
$("#contactResponse").html(data);
});
});
</script>
The email works but the php script is on the server, and it takes me to a different page.
Can someone please give me some suggestions/advice.
Thanks

Try this, it works for me
<script>
// Get the form.
var form = $('#contactForm');
// Get the messages div.
var formMessages = $('#contactResponse');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
// $('#subject').val('');
// $('#company').val('');
$('#message').val('');
$(form).hide();
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$( "#contact" ).children(".loading").remove();
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
</script>

Related

Refresh form after AJAX call

Background
I have an email sign-up form on a website.
The form appears in two areas of each web page: the header and the footer
It's the same exact form, just available on the top and bottom of the page for better UX and accessibility.
The form uses a jQuery/AJAX script to provide success and error responses to the user. (i.e., "Success! Your subscription is complete." and "Error. Please review and re-submit")
When the user submits the form, the user input is added to the database AND a notification email is sent to site admins.
If the header form is used, the email subject reads "Email Subscriber Added (Header Form)".
If the footer form is used, the subject reads "Email Subscriber Added (Footer Form)".
(This is just a simple technique to let admins gauge the usage of each form.)
Here's what the PHP looks like:
if ( $form_selected == 'header' ) {
$mail->Subject = 'Email Subscriber Added (Header Form)';
$mail->Body = $message;
} elseif ( $form_selected == 'footer' ) {
$mail->Subject = 'Email Subscriber Added (Footer Form)';
$mail->Body = $message;
} else {
$mail->Subject = 'Email Subscriber Added (form version unknown)';
$mail->Body = $message;
}
To this point, everything works fine.
The Problem
The problem is that, if the site user submits multiple email subscriptions in the same session, site admins get the else version in the PHP script above ("form version unknown"). This option should never be invoked during a normal session. But the page needs to be refreshed before the if and elseif options are considered again.
Question
Is there a way to solve this problem in the jQuery/AJAX script (see below)? I'm open to modifying the PHP, as well, if necessary.
$(function() {
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(this).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form
$('input').val('');
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<!-- simplified HTML -->
<form action="process_form.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="header">
<button type="submit" name="submit_subscription">Submit (Header)</button>
<p id="header-form-responses"></p>
</form>
<form action="process_form.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="footer">
<button type="submit" name="submit_subscription">Submit (Footer)</button>
<p id="footer-form-responses"></p>
</form>
If this contains the data which triggers those PHP if conditions:
<input type="hidden" name="formtarget" value="header">
Then this is explicitly clearing that data:
// clear form
$('input').val('');
Instead, only clear the fields you want to clear:
// clear form
$('input[type="email"]').val('');
Use $('input:not([type="hidden"])').val('') to exclude the hidden input from clearing. Your JS is clearing all inputs including your hidden inputs.
$(function() {
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(this).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form except hidden inputs
$('input:not([type="hidden"])').val('')
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<!-- simplified HTML -->
<form action="process_form.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="header">
<button type="submit" name="submit_subscription">Submit (Header)</button>
<p id="header-form-responses"></p>
</form>
<form action="process_form.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="footer">
<button type="submit" name="submit_subscription">Submit (Footer)</button>
<p id="footer-form-responses"></p>
</form>

how to refresh a particular div after jquery form submission [duplicate]

This question already has answers here:
Ajax - How refresh <DIV> after submit
(5 answers)
Closed 7 years ago.
// My jquery for form submission
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
// My form
<p>
<form action="" method="post" id="form1">
<input type="text" name="valuebox" placeholder="type your code" required />
<button name="submit" class="button1" type="submit" id="submit1">Apply</button>
</form>
</p>
<div class="alert1">Hello</div>
// giftcard_check.php
include("include/dbconnection.php");
dbconnect();
session_start();
$_SESSION['fromttl'] = 0;
$valuebox = $_POST['valuebox'];
$query = "SELECT * FROM db_coupon WHERE code='$valuebox' AND publish='1'";
$result = mysql_query($query);
$length = mysql_num_rows($result);
$rows = mysql_fetch_array($result);
$discount = $rows['discount'];
if($length == 1)
{
$_SESSION['fromttl'] = $discount;
echo $_SESSION['fromttl'];
}
else
{
$_SESSION['fromttl'] = 0;
echo "Invalid Gift Card!";
}
My question is how to refresh a particular div (ie,
<div id="show"><?php echo $_SESSION['fromttl']; ?></div>
) immediate after the form submission.
My current result not refreshing the particular div after form submission. I don't want to refresh whole page, only a particular div. If i refresh whole page the div will be refreshed.
Is there any solution? I am stuck here.
You should try this, put a return false;at the end of your form.on('submit',... it will not submit your form request and you will stay on the same page :
// My jquery for form submission
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
if(data != 'Invalid Gift Card!') {
$('div.show').html(data);
}
},
error: function(e) {
console.log(e)
}
});
return false; //Will not active the form submission
});
});
// My form
<p>
<form action="" method="post" id="form1">
<input type="text" name="valuebox" placeholder="type your code" required />
<button name="submit" class="button1" type="submit" id="submit1">Apply</button>
</form>
</p>
<div class="show"></div>
<div class="alert1">Hello</div>
After your form submission, you can clear the content of div as:
$("#show").html("");
Then, update the div content as you required.
empty the content of the division you want using jQuery empty()
for example if you want to clear that div after form reset then simply add
...
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
$('#show').empty(); // clear div from previous content
submit.html('Apply'); // reset submit button text
},
...
in case that "show" div needs not to be empty use html()

Disable form inputs after ajax submission

I have a form that submits via Ajax. After the user sends the form, the text changes displaying the form was sent successfully and then shows the form filled out. I want to display the form but I don't want them to re-submit the form so I want to disable the inputs as well as the submit button. I tried adding: $('#submit_btn').className +=" disabled" to the ajax script but it just made the page refresh without submitting anything.
The ajax script is as follows:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
var email = $("inputemail").val();
var phone = $("inputphone").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://www.green-panda.com/website/panda/webParts/contact-form.php",
data: dataString,
success: function() {
$('#myModalLabel').html("<h3 class='text-success' id='myModalLabel'>Contact Form Submitted!</h3>")
$('#myModalSmall').html("<p class='muted'>Your submiessions are below. We will be contacting you soon, you may now close this window.</p>")
$('#submit_btn').className +=" disabled"
.hide()
.fadeIn(1500, function() {
$('#message').append("<i class='icon-ok icon-white'></i>");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
How could I possibly disable the inputs and button after a successful form submission?
http://jsfiddle.net/gY9xS/
Actually it's a lot simpler than what you're trying to do, you don't need to disable the inputs, simply cancel the submit after the ajax request:
$('form').submit(function(){
return false;
});
Put it inside the success handler of your ajax request.
If you want to disable the submit button, replace this wrong thing:
$('#submit_btn').className +=" disabled"
With:
$('#submit_btn').prop("disabled", true);
In my application, i just disabled the submit button and shows some progress message
function submitForm(formObj) {
// Validate form
// if (formObj.email.value === '') {
// alert('Please enter a email');
// return false;
// }
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
return true;
}
<form class="form-login" accept-charset="UTF-8"
method="POST" action="/login" onsubmit="return submitForm(this);">
......
<input type="submit" id="login-submit" name="submit" value="Log In">
</form>

Posting form data Jquery

I am trying to build a mobile app but am having some trouble getting the basics of Jquery/Javascript.
I am trying to make it so I can type in any value I want into the input field and then post it, it would post above and allow me to type more into the input field and it would post above the last post.
Here is my code so far. Stumped where to go next or if I am going in the right direction.
<!DOCTYPE HTML>
<HTML>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$('#commentForm').submit(function(){ //listen for submit event
$.each(params, function(i,param){
$('<input />').attr('type', 'show')
.attr('value', param.value)
.appendTo('#commentForm');
});
return true;
});
</script>
<BODY>
<form id="commentForm" method="POST">
<textarea cols="30" rows="6" name="comment" title="Enter a comment">
</textarea>
<input type="submit" value="Post"/>
<input type="reset" value="Reset"/>
</form>
<div id="box">
</div>
</BODY>
</HTML>
Give the submit button an id called "submit"
function onSuccess(data, status) {
data = $.trim(data);
//make a div with id "notification" before running this code
$("#notification").html(data);
$.mobile.hidePageLoadingMsg(); //used on jquery mobile to hide a loader
}
function onError(data, status) {
data = $.trim(data);
$("#notification").html(data);
$.mobile.hidePageLoadingMsg(); //used on jquery mobile to hide a loader
}
$("#submit").click(function() {
$.mobile.showPageLoadingMsg(); //used on jquery mobile to show a loader
var formData = $("#commentForm").serialize(); //get all data from form
//do the POST thingies
$.ajax({
type: "POST",
url: "url_to_your_php_interpreter",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
});
I'm using this script to login an user.
PS: everything you will "echo" from php interpreter will be shown on div with id "notification" wich you will (probably) create

How to put a jQuery code into one file which will be referenced by all pages?

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

Categories

Resources