Due to language limitations I might not understood how to ask Google about what I want to accomplish, but I hope you will understand.
I have three forms which i want to show on the same page without refresh. First form submits action to php which determines which function (with yet another form) to show. But buttons interfere and I am nowhere near what I wanted to do.
Index.php is supposed to send user input to calculator.php which then opens next form depending on value:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
<div id="parseSecondForm"></div>
<script type="text/javascript">
$(function(){
$('#form1').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('formaction'),
data: $(this).serialize(),
beforeSend: function(){
$('#parseSecondForm').html('<img src="loading.gif" />');
},
success: function(data){
$('#parseSecondForm').html(data);
}
});
});
});
</script>
calculator.php receives user input and echoes next form in #parseSecondForm div in index.php:
if (form1 === '1') {
echo '
<form id="form2" method="post" formaction="form2.php">
<input id="form2" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
else {
echo '
<form id="form3" method="post" formaction="form3.php">
<input id="form3" type="submit" value="Submit" />
<div id="thankyou"></div>
<!--submit saves php result in MySQL and thanks the user in next div-->
';
}
I tried to echo modified javascript from index.php, but it just resets all the forms.
Maybe there are some form scripts designated for the cause or any other ideas how can I fix the issue?
In Javascript/HTML you cannot have two items with the same IDs:
<form id="form1" method="post" formaction="calculator.php">
<input id="form1" type="submit" value="Submit" />
form1 can be used only once.
Same for the php dynamically created forms.
Related
I have a signup form in my HTML file. The action of the form is a PHP file. I want the PHP to process the entered data and leave the user on the signup page (HTML.) However, when the submit button is clicked, the website redirects to the PHP file. Is there some way of preventing this?
I have tried setting the form's target to "_self", but that didn't help.
HTML:
<? include('signup.php'); ?>
<?php include('errors.php'); ?>
<form method="post" action="signup.php">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
you can actually leave that empty, so the same page gets targeted :)
Remove or blank the action attribute in form like as:
HTML:
<?php include('signup.php');
include('errors.php');
?>
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
</form>
If you don't want to refresh the page and handle user input you can use AJAX
Simple example:
<form>
<label for="username">
Username
<input type="text" id="username">
</label>
<label for="password">
Password
<input type="password" id="password">
</label>
<button id="submit"></button>
</form>
<script>
$(function () {
$('#submit').click(function () {
$.ajax({
method: 'POST',
url: 'signup.php',
data:
{
name: $('#username').val(),
password: $('#password').val()
}
}).done(function (msg) {
alert('Data Saved: ' + msg);
});
});
});
</script>
If you want to send POST request to the same page, just remove action attribute from the form
<form method="post">
***More Input fields here***
<button type="submit" name="submit">Sign Up</button>
I have a PHP page (page.php) that I am using to post data into my database. I am using the form method post to send the data to my database. Inside the <form> I have a second <form> which I use to upload an image.
But when I click on Upload the outer <form> will posted: action="./submit.php".
Does someone know how I can fix this?
Here is my script:
page.php
<form name="reaction" method="post" action="./submit.php">
//multiple textboxes
//upload script
<form name="newad" method="post" enctype="multipart/form-data" action="page.php">
<table style="width:100%">
<tr><td><input type="file" name="image" value="Choose file"></td></tr>
<tr><td><br /><input name="Submit" class="btn2" type="submit" value="Upload"></td></tr>
</table>
</form>
<button type="submit">Post page</button>
</form>
well Ryan is right, you can't have a <form> inside a <form> my suggestion is change the html stucture or make it into one <form> with one action and maybe you can split the function inside submit.php
You can't have nested form like this in HTML.Follow this instruction to better undrestanding about form handling in PHP.
You can use two submit buttons in one form, they can each have a different formaction to specify where to submit.
<form name="reaction" method="post" enctype="multipart/form-data">
//multiple textboxes
//upload script
<table style="width:100%">
<tr><td><input type="file" name="image" value="Choose file"></td></tr>
<tr><td><br /><input name="Submit" class="btn2" type="submit" value="Upload" formaction="page.php"></td></tr>
</table>
<button type="submit" formaction="submit.php">Post page</button>
</form>
Both buttons will submit all the form fields, but the two scripts can simply ignore the fields that they don't care about.
Recommendations:
Step 1: separate each form
Step 2: give each form an id
Step 3: use jquery's $.ajax() to publish the forms to their respective targets URLs
Example of Ajax call:
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
Code from hog I was lazy to write one
After I submit my data from form I don't see it immediate on my screen, I have to refresh it via browser refresh button.
<form action="" method="post">
<input type="submit" name="submit" >
I was using the setTimeout function but it gave me lot of issues in submitting to the database and retrieving from it. I could not debug it properly, and so I removed this function. Without setTimeout, I am able to store in the database and retrieve via the refresh button. But how do I make it immediately auto refresh?
i have done with the help of jquery and ajax without refresh and page loading
html file with ajax
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#sub").click(function(){
$.ajax({
url: 'dbadd.php',
type: 'POST',
data: {naam:$("#nm").val()},
success:function(response){
$("#d1").html(response)
}
});
});
});
</script>
</head>
<form method="post">
Name : <input type="text" id="nm" name="name">
<div id="d1"></div>
<input type="button" name="submit" id="sub" value="submit">
</form>
</html>
php file : adddb.php
<?php
$con=mysql_connect("localhost","root");
mysql_select_db("empl",$con);
$q=mysql_query("insert into emp(name) values ('".$_POST['naam']."')");
$qq=mysql_query("select name from emp where name='".$_POST['naam']."'");
while ($data=mysql_fetch_object($qq)) {
echo $data->name;
}
?>
For refresh page use this code:
<META HTTP-EQUIV ='Refresh' Content ='0; URL =/'>
You can use like this end of your code:
<?php echo "<META HTTP-EQUIV ='Refresh' Content ='0; URL =/'>"; ?>
Set your action as:
<?php echo $_SERVER['PHP_SELF']?>
and it will do the trick.
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
Action is the directive that trigger what to do with the data. If you don't specify it how is the browser supposed to do anithing?
I have a website started where I want to have 2 separate submit buttons, one of which will take data entered and do some calculations to it to display on the same screen. I've got this successfully working with:
<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">
and then I use:
if (!isset($_POST['submit'])){
Do actions, display calculations}
Now I want a second submit button that still grabs the data they entered but then goes to a different address. Is there an elegant way to do this?
You could add an onclick method to the new submit button that will change the action of the form and then submit it.
<script type="text/javascript">
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
}
</script>
...
<form id="form1">
<!-- ... -->
<input type="button" onclick="submitForm('page1.php')" value="submit 1" />
<input type="button" onclick="submitForm('page2.php')" value="submit 2" />
</form>
You can change the form action by using formaction="page1.php" in button property .
<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">
<input type="button" type="submit" formaction="page1.php">Action 0</button>
<input type="button" type="submit" formaction="page2.php">Action 1</button>
</form>
Note: The formaction attribute of the button tag is not supported in Internet Explorer 9 and earlier versions.
The best way to deal with multiple submit button is using switch case in action script
<form action="demo_form.php" method="get">
Choose your favorite subject:
<button name="subject" type="submit" value="html">HTML</button>
<button name="subject" type="submit" value="css">CSS</button>
<button name="subject" type="submit" value="javascript">Java Script</button>
<button name="subject" type="submit" value="jquery">jQuery</button>
</form>
Action / Server Side script:
demo_form.php
<?php
switch($_REQUEST['subject']) {
case 'html': //action for html here
break;
case 'css': //action for css here
break;
case 'javascript': //action for javascript here
break;
case 'jquery': //action for jquery here
break;
}
?>
Ref: W3Schools
Another approach is that You can create and Use some session variable to achieve it easily.
E.g. $_SESSION['validate'].
HTML and PHP Code for buttons
<button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>
jquery and ajax Script
<script>
$(document).ready(function(){
$("#form").on('submit', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'handler-file.php',
data: new FormData(this),
dataType: "json",
enctype: 'multipart/form-data',
contentType: false,
cache: false,
processData:false,
error:function(error){
//your required code or alert
alert(error.responseText);
},
success: function(response){
if(response.status=='1')
{
//your required code or alert
$('#first_submit').hide();
$('#second_submit').show();
}
else if(response.status=='2')
{
//your required code or alert
$('#first_submit').show();
$('#second_submit').hide();
}
else
{
//your required code or alert
}
}
});
});
});
</script>
Handler PHP File
<?php
session_start();
$result['status']='0';
$result['error']='';
if(!isset($_SESSION['validate']))
{
if(!isset($_FILES['file']))
{
$result['error'].='[Er-02 file missing!]';
}
else
{
//your other code
$_SESSION['validate'] = true;
$result['status']='1';
}
}
else if($_SESSION['validate']==true)
{
if(!isset($_FILES['file']))
{
$result['error'].='[Er-03 Validation file missing!]';
}
else
{
//your other code
unset($_SESSION['validate']);
$result['status']='2';
}
}
else
{
$result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result);
?>
It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.
Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.
Hope it helps!
I have any page for answer/question. i retrieve list of question for admin. admin see this. now i need to send answer to each question. so i for each question put textarea and form with post action. now i need to when send answer of question message, if send message to external php files = true; of message(ID) remove(jquery slideup effect). for this i have jquery submit form code ( without refresh page ) but I have big problem. this worked ONLY with one form ! and not worked for all list form ( question + answer form ) . how to worked my code for multiple form ? I chose the right way?
html code :
<form action="insert.php?id=42" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=45" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=48" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=50" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
Thanks
Your major issue is probably that you are trying to reuse ids. All the forms have the id of "forms" and you are also sharing the id "box".
All ids should uniquely identify an element. Use a class when you need to classify an element. I'd recommend you change id="forms" on all the forms to class="reply_form" and then also change id="box" on all the divs to class="reply_box". Then change styles set for #forms and #box to those set for .reply_form and .reply instead.
EDIT - tweaks made in jsfiddle after some discussion with the OP.
http://jsfiddle.net/gvnfg/5/
just change the selector. id attribute must be unique in html
$("[name='form']").submit(function() {
$this = $(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
cache: false,
beforeSend: function() {
$('#loading').show();
$('#result').hide();
},
success: function(data) {
if(data==1){
$('#loading').hide();
$('#result').fadeIn('slow').html("ok");
$('#result').addClass('true');
$this.slideUp(1000);
}
else {
$('#loading').hide();
$('#result').fadeIn('slow').html(data);
$('#result').addClass('errors');
}}
});
e.preventDefault();
return false;
});
use Jquery .each() method:
$(document).ready(function() {
$('#forms').each(function() {
this.submit(function() {
$.ajax({ ... });
});
});
})