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

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

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>

javascript not posting form with ajax [duplicate]

This question already has answers here:
Duplicate form submission whtn button clicked?
(2 answers)
Closed 5 years ago.
I have a javascript to post a form using ajax but it keeps giving me an error. It is triggered from a bootstrap button but does not seem to do anything?
The button is :
<button id='btn-finish' name ='btn-finish' type='button' class='btn btn-primary'>Finish</button>
and the js is :-
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $(this);
$.ajax({
url: form.attr('process-form3.php'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
// $('#5box').hide();
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
You must have to get Form id not a button Id, you have written code for getting button id instead of form object.
code should be like for example:
<form id='test_form' action='path' method='post'>
<button id='btn-finish' name ='btn-finish' type='button' class='btn btn-primary'>Finish</button>
</form>
your jquery code :
$(document).ready(function() {
$('#btn-finish').on('click', function() {
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Processing...');
var form = $('#test_form');
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
// $('#5box').hide();
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});

Form submission js/jquery staying on same page

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>

PHP code inside jquery not working

//My jquery
$(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
var $container = $("#result1");
var refreshId = setInterval(function()
{
$container.load("result.php?code=<?php echo $variable; ?>");
}, 500);
},
error: function(e) {
console.log(e)
}
});
});
});
The above code is not working while using php code inside jquery. If iam not using php code its working fine. But i want to send session variables to another page (result.php). How can i solve this. Is there any method.
use below code . assing php session to javascript variable. make sure this code is in side PHP file . php will not work inside .js file
var sessionID = "<?php echo $_SESSION['id']; ?>";
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
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
var $container = $("#result1");
var refreshId = setInterval(function()
{
$container.load("result.php?code="+sessionID);
}, 500);
},
error: function(e) {
console.log(e)
}
});
});
});
lets look on a different angle
you can do on your html something like this:
<form>
<input type="submit" id="f_the_world" data-session-id="<?php echo $variable; ?>"/>
</form>
then on your JS
$(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
var $container = $("#result1");
var refreshId = setInterval(function()
{
var code = $('#f_the_world').attr('data-session-id');
$container.load("result.php?code=".code);
}, 500);
},
error: function(e) {
console.log(e)
}
});
});
});
its just dont feel right seeing server scripts on client scripts
why are you sending the session id to the next page...session values are stored
in server. You can access session values from any page.
we can easily get the session variable in result.php by adding session_start(); at the begining of result.php. So that we can have access to the session variable created.
First Step:
In your jQuery code written page just start the session variable $_SESSION['id'].
Second Step:
In your result.php page, write session_start(); at the beginning. Then just call the $_SESSION['id'].
Hope this will help :-)

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>

Categories

Resources