I am trying to show a hidden div after submitting a form data
Below is my form html where the input section will have a form to enter the data and after submitting the form I have to show hidden output section and show result there
html code:
<div id="input">
----- some form datas here ----
<div id="submit">
<input type="submit" id="generate" name="script" value="generate" />
</div>
</div>
<div id="output" style="display: none;">
--- php echo from above form------
</div>
</form>
css:
#input{
width:800px;
margin: auto;
border-width:1px;
border-style:solid;
border-color:#ddd;
}
#output{
width:800px;
margin: auto;
border-width:1px;
border-style:solid;
border-color:#ddd;
}
After going through some previous discussion about the same topics, below is one of the answered solution for this
create a JavaScript like to show the hidden div after form submission.
$('form').submit(function(){
$('#output').show();
});
or
$('form').submit(function(e){
$('#output').hide();
e.preventDefault();
// Or with: return false;
});
But both the solutions are not working for me.the second is able to show the hidden div output but it not showing actual form data.
How can I show it correctly ? I need to show this after form submission (type="submit")
UPDATE:
Removed the inline css to hide div
Added css function in style sheet to hide div
#output{
display:none;
width:800px;
margin: auto;
border-width:1px;
border-style:solid;
border-color:#ddd;
}
Added below jquery to show div on form submit
$('form').submit(function(){
$('#output').css({
'display' : 'block'
});
});
Still I an not able to achieve the result. Any clue here ?
use
<form id="form" action="">
</form>
To display output
$(document).ready(function() {
$('#output').hide();
$('#form').submit(function(){
$('#output').show();
});
});
$('form').submit(function(e){
$('#doutput').hide();
e.preventDefault();
// Or with: return false;
});
Here in your script you are spelling doutput. replace it with output
and to show use .css() function and define display: block !important; because you have displayed it in your inline style so to override this you need to set !important.
Alternatively, define display: none; in the stylesheet instead of using in inline style and do the rest without setting !important
Remove Display: none;
And do this code
$('form').submit(function(e){
$('#doutput').hide();
e.preventDefault();
// Or with: return false;
});
to hide and
$('form').submit(function(e){
$('#doutput').hide();
e.preventDefault();
// Or with: return false;
});
to show
You could use .hide() and .show() as opposed to editing CSS attributes via .css().
$('document').ready(function() {
$('#output').hide();
$('form').submit(function(e) {
$('#output').show();
e.preventDefault();
});
});
if you want to show results within the DIV, there are many ways to do this.
Javascript
Give all your form data an ID, and then write a javascript function to fill the answers in the said DIV.
Ajax
Post your form to ajax, return the response to your DIV
New page request
After submitting, check to see if $_POST is set and then show the div with $_POST contents.
If I got it right you don't want to reload the page.
In this case you need to send the form data via ajax call.
Than you can display the response and the hidden div.
CSS
#output {
display:none;
}
jQuery
$(document).ready(function(){
$('form').submit(function(e){
// Prevent the default submit
e.preventDefault();
// Collect the data from the form
var formData = $('form').serialize();
//Send the from
$.ajax({
type: "POST",
url: "generator.php",
data: formData,
success: function(msg){
// Insert the response into the div
$('#ajaxResponse').html(msg);
// Show the hidden output div
$('#output').slideDown();
}
});
});
});
HTML
<div id="output">
--- php echo from above form------
<div id="ajaxResponse"></div>
</div>
You could try using the "action" attribute of the form element or you could try the jquery serializeArray method at the form element right after the submit.
<form>
<input type="text" name="giveNameHere" />
<input type="submit" id="generate" name="script" value="generate" />
</form>
<div id="output" style="display: none;">
Output Content
</div>
$('form').submit(function () {
$('#output').show();
console.log($(this).serializeArray());
return false;
});
Please see this jsfiddle
Related
I have an HTML form like the one shown below, which after submitting is processed by PHP:
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST" enctype="multipart/form-data" id="decisions_form">
<!-- ... -->
<div style="text-align:center;">
<input type="submit" name="submit" value="Submit Decisions" id="decisions_button">
</div>
</form>
PHP does some processing, which could take a few seconds. After processing is complete, I refresh the page as below (probably not best practice, I don't know):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// PHP...
}
echo ('<meta http-equiv="refresh" content="0.1;">');
?>
I would like to show a full-screen "loader/spinner", which would be activated after submitting and during PHP processing. Normally, If I understand it correctly, this loader/spinner should be interrupted by the refresh page command -- which is what I want
Looking for such loaders was unsuccessful, if not totally confusing for a inexperienced person like me.
It would be ideal if I could avoid JS and do it in a pure HTML/CSS fashion (is it even possible?).
I am not aware of a mechanism to do it in pure HTML. There are probably other and more sophisticated ways to do it than what I show below, but this worked well for me. Every time you place a call to the server, the ajax start function executes and delays 1 second (change the delay however you want) and then displays the waiting gif. When the ajaxStop function is called upon completion of the server call and stops the wait gif and enables the buttons. Note this should be the first tag in your html file after the css definitions.
Javascript code
<script defer>
$( document ).ready(function() {
// gif on 1 second timer delay before displaying, so user does not have it appear to quickly if the delay is short.
var loadingTimer;
$(document).ajaxStart(function() {
$(':button').prop('disabled', true); // disable all the buttons
loadingTimer = setTimeout("$('#process-wait').show()", 1000); // show the waiting gif
});
$(document).ajaxStop(function() {
clearTimeout(loadingTimer);
$("#process-wait").hide(); // hide the waiting gif
$(':button').prop('disabled', false); // enable all the buttons
});
});
</script>
Here is the css you need to go along with that. You can make it as big as you want, by adjusting the height and width values. Pick your own gif image simply set the url parameter to the directory path and name of the gif file.
#process-wait {
background: transparent url(images/process-wait.gif);
background-repeat: no-repeat;
height: 150px;
width: 150px;
z-index: 99999;
display:none;
position: absolute;
top: 50%;
left: 50%;
margin-left: 10px;
margin-top: 0px;
transform: translate(-50%, -50%);
Here's a complete example:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
header("Content-Type: application/json");
echo json_encode($_SERVER);
exit;
}
?>
<!doctype html>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
<div hidden class="spinner-border text-primary" role="status">
<span class="sr-only">Loading...</span>
</div>
<form action="<?php print $_SERVER['PHP_SELF'] ?>" method="POST" enctype="multipart/form-data" id="decisions_form">
<input type="text" name="dummy" value="dummy value">
<!-- ... -->
<div style="text-align:center;">
<input type="submit" name="submit" value="Submit Decisions" id="decisions_button">
</div>
</form>
<div class="complete" hidden>
Submission received<br>
<button class="reset">Reset</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
<script>
window.addEventListener('load', () => {
const decisionsForm = document.querySelector('#decisions_form');
const spinner = document.querySelector('.spinner-border');
const complete = document.querySelector('.complete');
const resetButton = document.querySelector('.reset');
// Show spinner, hide form
function formSending() {
spinner.removeAttribute('hidden');
decisionsForm.style.display = 'none';
}
// Hide spinner, show complete message
function formSent() {
complete.removeAttribute("hidden");
spinner.setAttribute("hidden", true);
}
// Show form, hide everything else
function reset() {
decisionsForm.style.display = 'block';
spinner.setAttribute("hidden", true);
complete.setAttribute("hidden", true);
}
// Send form data in the background
async function submitDecisionsForm(event) {
// Display spinner
formSending();
// Collect data to send
// event.target = the form
// event.target.action the action property on <form action="">
// the POST body gets set by reading the data from the form object (event.target)
const response = await fetch(event.target.action, {method: "POST", body: new FormData(event.target)});
// Submit is complete.. show the complete message and reset button
formSent();
// Format the response if you want to use it later
const responseJson = await response.json(); // or response.text() depending on what send back from the server
// Output to browser's dev console for debugging
console.log(text);
}
// Capture submit event
decisionsForm.addEventListener("submit", (event) => {
// Stop form from submitting immediately by default
event.preventDefault();
// Send form data in the background
submitDecisionsForm(event);
});
// demo: reset the form when clicking the reset button
resetButton.addEventListener('click', reset);
});
</script>
See comments in the code for explanation of parts.
I have a strange problem that is driving me crazy!
I'd like to submit a HTML form by ajax using jquery-form version 3.46.0 and then get the POST data on server, but my Submit button's name won't show up in the POST data! Maybe there's something wrong with this lib?
This my code:
<form id="form" action="test.php" method="post">
<input name="email" type="email" placeholder="Email" required>
<!-- And yes! I didn't use an input with type submit because
I need my button to have some HTML content and applied css styles to them. -->
<button id="submit" type="submit" name="myFormName">
<span class="label">Submit</span>
</button>
</form>
<div id="formResult" style="display: block; margin: 20px 0; padding: 10px; background-color: #fbe6e6;" role="alert"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="//oss.maxcdn.com/jquery.form/3.50/jquery.form.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('#submit').on('click', function(e) {
e.preventDefault();
$('#form').ajaxSubmit({
clearForm: true,
target: '#formResult',
success: function() {
// do sth
},
error: function() {
// do sth
}
});
});
});
</script>
And this is the test.php file:
<?php
var_dump($_POST);
I need the name of my Submit button appear in POST data on server as expected... But it doesn't! Does anybody have any idea?
If you use name for button, then while taking as $_POST, the value will be shown as post data. Instead of using name try using id or simply remove that if you don't have any use of that
We can solve this by following ways -
Use jquery form plugin and it will post all form data
If you are not using the above or any plugin then simply append submit button name to the form serialize as below:
$('#myForm').submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "process.php",
data: $('#myForm').serialize()+"&btnSubmitName=true",
success: function(response){
$('#resultDiv').html(response);
}
});
});
<div><a href="javascript:foo1()">
<div class="holder"><span class="label">Submit</span></div>
<div class="loader"><i class="fa fa-circle-o-notch fa-spin"></i></div></a></div>
And implement foo1 to submit the form.
I'm trying to change the content of div using jquery. but the content flashes and resets the div. i cannot use return false; because there is another button for post text field value. i want to keep the changes of div. here is my code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div>
<form id="form" method="POST">
<input type="text" name="gname" id="gname"/></br>
<button id="btn">Set</button>
<button id="nbtn">View</button>
</form>
</div>
<div id="outp">
</div>
</body>
<script>
$("#btn").click(function(event) {
$.post("send.php", {
named: $("#gname").val()}, function(data) {
alert(data);
});
});
</script>
<script>
$("#nbtn").click(function(e) {
$("#outp").html("<?php include './view.php'; ?>");
});
</script>
It's not jQuery; it's that your form is being posted. So your change is made, but then the form is posted and the page is refreshed from the server.
The default type of button elements is "submit". To make one or both of those buttons just a button, use type="button".
Alternately, if you want to allow the form to be used when JavaScript is disabled (e.g., allow it to be posted normally), leave the buttons as submit buttons but prevent form submission using JavaScript. E.g.:
$("#form").submit(false); // Prevents the form being submitted in the normal way.
Any buttons inside a form are considered submit buttons.
So you need to add event.preventDefault() to your .click code.
Also, why are your scripts outside body section?
You can try with ajax and catch success and error:
$("#btn").click(function() {
var named: $("#gname").val();
$.ajax({
url: 'send.php',
type: 'POST',
data: {param1: 'value1'},
})
.done(function(data) {
console.log("Post success"+data);
})
.fail(function() {
console.log("Post error"+data);
});
});
I am new to ajax.
I have index.html
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"n.php",success:function(result){
$("#div1").html(result);
}});
});
});
</script>
<div id="div1" style="margin-left: 25;"></div>
<button>Add Author</button>
n.php
Name:<input type="text" name="txtname">
age:<input type="text" name="txtage">
Simply i want to add name and age textboxes on index.html page when 'Add Author' button clicks without refreshing page.But above code loads name and age textboxes only once.I want it every time when button clicks.
Edit:
Now if I want to put another button 'remove author',and want to perform exact opposite action(i.e) remove both textboxes.what should i do? can u please help?
and want to know how can i check validation server side?
Please Help.
Change this
$("#div1").html(result);
to
$("#div1").append(result);
So everytime you click the button it will append the textboxes.
try the following:
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"n.php",success:function(result){
$("#div1").append(result);
}});
});
});
</script>
use append instead of html. append will add the response at the end of whatever content is present in the div wherease html will replace the present content.
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url:"n.php",success:function(result){
$("#div1").append(result);
}});
});
});
</script>
<div id="div1" style="margin-left: 25;"></div>
<button>Add Author</button>
I have a div with a form in it. After a user submits the form, I want to load new content into the div, replacing the form.
The new content will be static.
Do I need AJAX for this?
you don't HAVE to use ajax for this, after submitting the form you can issue a redirect to a static page without the form(post-redirect-get pattern).
But note that in this case the entire page will refresh while submitting,
and if the submit might fail from some reason(who said validation), hitting F5 will pop up the ugly "do you want to send crap..."
so no, you don't have to use ajax, but it is so easy with the form plugin that it is a crime not to.
if you do use the form plugin, then at the success callback hide the form with the static content
You do need Ajax: (I'll do it like SimpleCoder said, but with the ajax call)
$('#myForm').submit(function(){
var field1 = $("#field1").serialize(); // If this doesn't work just remove the serialize()
var field2 = $("#field2").serialize();
$.ajax({
type: "POST",
url : "???", //your processing page URL instead of ???
data: "&field1="+field1+"&field2="+field2,
success: function(){
$("#formHolder").html("Your static content");
}
});
});
( You should replace field1, field2 with your fields, and if it doesn't work, remove the serialize() function. )
All you have to do is .html() the static content in the success function of the ajax call.
Assuming your HTML looks something like this:
<div id="formHolder">
<form id="myForm">
...
</form>
</div>
Do something like this:
$("#myForm").submit(function(){
$("#formHolder").html("Your static content");
});
You can find an example of this here
https://www.write-about-property.com/seo-services/ the code to work on the form submit uses an instance of the object created in form.js
If you have a crack at it then come back we will help you perfect it for your purpose. You would put the div you wanted to update in the toupdate var
ajform.toupdate = $("#update")
you can simply make the divs invisible, and the submit button is just a button with js action to make the div visible
<script type="text/javascript" language="javascript">
function step2() {
document.getElementById('step1_container').style.display = 'none';
document.getElementById('step2_container').style.display = 'block';
}
function step3() {
document.getElementById('step2_container').style.display = 'none';
document.getElementById('step3_container').style.display = 'block';
}
</script>
...
<form action="validate.php" method="post">
<div id="step1_container">
PAGE 1 here
<input type="button" onclick="javascript:step2();" value="submit"/>
</div>
<div id="step2_container" style="display: none;">
Page 2 here
<input type="button" onclick="javascript:step3();" value="submit"/>
</div>
<div id="step3_container" style="display: none;">
Page 3 here
<input type="button" onclick="javascript:step4();" value="submit"/>
</div>
</form>
And so on
You don't need ajax, using only on-page javascript would be enough.
However, with ajax you can display the content from the page you're submitting the form to.
Try the jQuery From plugin for an elegant ajax solution:
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
});
});
</script>