I got a code here that if I refreshed the page it automaticaly save the data....can anyone help me that it will only save if the submit button is clicked.
current code:
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $var; ?>" />
<input type="submit" name="save">
</form>
</body>
</html>
The code you show is from your "handling" page. That page handles the post, it checks if there was a parameter "save" and if so, it saves.
If the user refreshes that page, he visits the page again, sending again a "save" parameter, so the INSERT is done twice.
To avoid this, you should use the POST-REDIRECT-GET model, where your handling page gets the data, saves it, and then redirects the user to a "GET" page (no post, no insert) that just shows the data. If the user then hits refresh, he only refreshes the "GET" page.
Offcourse, a user can always keep using the BACK button to go to the actual insert page. His browser will warn him "you are resubmitting form data...", but if he chooses to, he can. If you really want to handle this, you can work with session keys: have an extra field "submitID" on your form, and on INSERT, first check if that ID was already "used". You'll need an extra table/column "submitID" somewhere to ensure a form can only be submitted once.
The problem is the form is getting submitted again, you can make header redirect to this same page,
header("location: index.php) after updating your database and this will solve your issue.
Create one button in html
<input type="submit" name="submit"/>
In php Code, you can write like
<?php
if(isset($_POST['submit']))
{
//place your total code here
}
?>
As soon as the form is submitted once it has got the $_POST-Array in the site request. When you reload the page after the first submit, it will always send the data again.
You got multiple possibilities to resolve this problem:
1)
Reload the page after the execution of the PHP code. To do so put the PHP code at the top of the page (before writing anything in HTML) and reload the page after the execution of the query:
if(isset($_POST["save"])) {
/* MySQL Query */
$back = $_SERVER['HTTP_REFERER'] ; // the site who called this site
header("Location: $back") ; // Link back to this site
}
2)
Personally I prefer to execute my PHP scripts with an Ajax call, which would look as follows in jQuery.
function ajaxCall()
{
$.ajax({
type: "POST",
url: "handler.php",
data: {save: 1, textfield: $("#textfield").val()}
}) ;
}
Don't forget, that the forms action isn't the redirect to another site anymore, it is the call to this function ajaxCall. If you want more fields to submit, have a look at the serialize-function. The handler.php-file contains only your php-Code:
<?php
ob_start();
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
exit(0) ;
?>
In the ajax function you could also handle what happens when the call is successful (e.g. redirect). Have a look at the $.ajax-reference of jQuery. If you want you could also use ajax without jQuery.
3)
You could also make your page in action similiar to the handler.php in the second possibility.
<form action="handler.php" method="POST"></form>
In this case you had to replace the exit-statement with the $back and header-call in possibility 1 (similar to the response of Konerak).
Related
Okay so I have an html form in Add.html. When I click submit, I would like the data to be added to my database via php and then return to the same form with "instance added" or "failed blah blah."
The only way I know how is to set the form action to a separate php file and call that - but then the php file renders and I do not return to the same form.
I would like to not have to add a "return to form" button and would prefer to return to the form on submit with a status message.
Any better ways to do this?
A very simple way to do is to do following :
yourpage.php
<?php
if(isset($_POST)){
//data posted , save it to the database
//display message etc
}
?>
<form method="post" action="yourpage.php" >....
You can do a redirect in php, to the html form - and you can set a "flash message" - to show "instance added" by saving "instance added" to the session and showing that value when you redirect to html.
you can use this trick
<?php if (!isset $_POST['Nameofyourinput']){
?>
<form method="post" action="add.html">
// your inputs here along with the rest of html
</form>
<?php
}
else
{
// Update you database and do your things here
//in your request variable you can add the error you want if things didn't go well, for example
$result = mysqli_query($connection, $sql) or die('Instance not added !'.$req.'<br>'.mysql_error());
// and then
echo (" instance added")
};
The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".
Just give nothing to the action attribute. It will refer to your current page.
<form method="post" action="">
Other way to do this are:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Or just add '#'
<from method="post" action="#">
To handle php code. Write your code inside it.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// write your code here.
}
You should change your file extension from .html to .php .
Well you can employ old school AJAX. For instance,let's say we have a form that takes in a number N,and once we click the calculate button we should see the result the of 2^N displayed on the same page without the page being refreshed and the previous contents remaining in the same place. Here's the code
<html>
<head>
<title> Simple Math Example</title>
<script type="text/javascript">
var request = new XMLHttpRequest();
function createAjaxObject(){
request.onreadystatechange = applyChange;
request.open("POST","calculate.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("N="+document.getElementById('N').value);
}
function applyChange(){
if(request.status == 200 && request.readyState == 4){
document.getElementById('resultSpace').innerHTML = request.responseText;
}
}
</script>
</head>
<body>
<fieldset>
<legend>Enter N to get the value of 2<sup>N</sup> ::: </legend>
<input type="text" name = "N" id = "N">
<br>
<input type="button" value = "Calculate" onclick="createAjaxObject()">
</fieldset>
<div id="resultSpace">
</div>
</body>
The file calculate.php is the same file with the above code. When the calculate button is clicked, it calls a function createAjaxObject which takes in a value N and sends the value to the same file via the POST method. Once the calculation is done, a response will be sent. And if the response is successful, it will be sent to a function called applyChange which will render it to the same page via JavaScript.
Is there any way to know if the page was refreshed or data was posted data on the same page?
To be little more specific:
I have to post data on the same page.
This affects the where condition of the query.
If the page was refreshed, then the where condition must be 1.
Otherwise, where condition contains some id to get specific data from
the table.
Your best bet is to use PHP sessions, along with your submitted data in $_POST. Let's presume for this example you have the following form:
<form action="this_page.php" method="post">
<input type="text" name="important-info" />
<input type="submit" value="Submit" />
</form>
Then elsewhere in the same page is the PHP code:
<?php
// example code
session_start();
if (!isset($_SESSION['previousVisitor']) && isset($_POST['important-info'])) {
// this is a new visitor who has submitted the form
$_SESSION['previousVisitor'] = true;
// where is based on $_POST['important-info']
} else () {
// where is 1
}
// close the session after you do what you need - this stops large pages causing hang
session_destroy();
Please note that they can clear this session variable by deleting their cookies.
on the top of the page just include
if(isset($_POST['name']) && $_POST['name']!=''){
//your code goes here
}
I suggest you to check request
//Here goes the code
session_start();
$counter = 0;
$counter = (isset($_SESSION['param'])) ? $counter++ : 0;
if($counter == 0)
echo "data GET or POST";
else
echo "refreshed";
** If you want only POST param, use $_POST instead of $_REQUEST
I'm a beginner in PHP. In my code, i want the php script to be executed only when the submit button is clicked (set). So when the page is refreshed, the isset() function should return false. Here is the code for test.php
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else{
$username = "";
}
?>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="test.php">
<Input Type = "text" Value ="<?php print $username?>" Name ="username">
<Input Type = "Submit" Name = "Submit1" Value = "Login">
</form>
</body>
</html>
After clicking the login button the script is executed and the output is "You are not a member", but when i refresh the page,the message from the script still remains on the screen. I believe isset() should return false until i click the button again? What's wrong with the code.
Thanks.
Realized that my comment was really an answer...
When you "refresh", you refresh the page INCLUDING the POST data (since that was the last "request" made). You would have to re-enter the address of the page to clear it. Sometimes you see "do you really want to send this form again?" prompt when you refresh - this is why...
Isset() is used to check if a variable example : $variable is actually "set" and is not null. Also when doing a refresh you also refresh the action you have committed and the form data that you have passed. You can think of it as this :
If you go to a shopping website and they tell you to not refresh while your order is processing that means that if you refresh your post data is submitted again meaning you buy 2 microwaves rather then 1 :)
So in coding it will look like this :
if (isset('$_POST['username']')) {
$username = $_POST['username'];
if($username == 'letmein') {
echo ("welcome back, friend!");
}
}
Hopefully this helps a bit. Good luck! Also if your ever on the "John" and need reading material take a look at the php manual page!
Refreshing the page will post the already posted form variables again so every time you refresh your page you are re submitting your form and by this you will have always the isset condition to true :)
I f you need more explaining tell me :)
I am trying to create a multi steps form where user will fill the form on page1.php and by submitting can go to page2.php to the next 'form'. What would be the easiest way?
Here is my code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
?>
<form id="pdf" method="post">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
if ($_POST["pr_name"]!="")
{
// data collection
$prname = $_POST["pr_name"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, enddate, sel, content) VALUES(?,?,?,?)");
if (!$stmt) echo "\nPDO::errorInfo():\n";
$stmt->execute(array($prname,$prend, $prmenu, $prcontent));
}
// somehow I need to check this
if (data inserted ok) {
header("Location: pr-pdf2.php");
}
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
I have changed following Marc advise, but I don't know how to check if the SQL INSERT was OK.
Could give someone give me some hint on this?
thanks in advance
Andras
the solution as I could not answer to my question (timed out:):
Here is my final code, can be a little bit simple but it works and there are possibilities to check and upgrade later. Thanks to everyone especially Marc.
<form id="pdf" method="post" action="pr-pdf1.php">
New project name:<input type="text" name="pr_name" placeholder="new project name..."><br/>
Email subject:<input type="text" name="pr_subject" placeholder="must be filled..."><br/>
New project end date:<input id="datepicker" type="text" name="pr_end" placeholder="yyyy-mm-dd..."><br/>
<textarea class="ckeditor" name="pagecontent" id="pagecontent"></textarea>
<?php
include_once "ckeditor/ckeditor.php";
$CKEditor = new CKEditor();
$CKEditor->basePath = 'ckeditor/';
// Set global configuration (will be used by all instances of CKEditor).
$CKEditor->config['width'] = 600;
// Change default textarea attributes
$CKEditor->textareaAttributes = array(“cols” => 80, “rows” => 10);
$CKEditor->replace("pagecontent");
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// data collection
$prname = $_POST["pr_name"];
$prsubject = $_POST["pr_subject"];
$prend = $_POST["pr_end"];
$prmenu = "pdf";
$prcontent = $_POST["pagecontent"];
//SQL INSERT with error checking for test
$stmt = $pdo->prepare("INSERT INTO projects (prname, subject, enddate, sel, content) VALUES(?,?,?,?,?)");
// error checking
if (!$stmt) echo "\nPDO::errorInfo():\n";
// SQL command check...
if ($stmt->execute(array($prname, $prsubject, $prend, $prmenu, $prcontent))){
header("Location: pr-pdf2.php");
}
else{
echo"Try again because of the SQL INSERT failing...";
};
}
$sbmt_caption = "continue ->";
?>
<input id="submitButton" name="submit_name" type="submit" value="<?php echo $sbmt_caption?>"/>
</form>
Add the attribute action with the url you'd like to go to. In this case it'd be
<form id="pdf" method="post" action="page2.php">
EDIT: i missed you saying this method doesn't work. What part of it doesn't work?
You should keep the action to the same script, so the POST action is still performed and then redirect with header("Location: page2.php"); when the processing is done.
A basic structure like this will do it:
form1.php:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... process form data here ...
if (form data ok) {
... insert into database ...
}
if (data inserted ok) {
header("Location: form2.php");
}
}
?>
... display page #1 form here ...
And then the same basic structure for each subsequent page. Always submit the form back to the page it came from, and redirect to the next page if everything's ok.
You're probably better off separating the php code from the form. Put the php code in a file called submit.php, set the form action equal to submit.php, and then add the line header('Location: whateverurl.com'); to your code.
The easiest way is to post it to form2.php by giving the form the attribute action="page2.php". But there's a risk in that. It means that form2 must parse the posted data of form1. Also, if the data is wrong (verification) form1 must be shown instead of form2. This will make your code over complicated and creates dependencies between the two forms.
So the better solution (and quite easy as well) is to implement the post-redirect-get pattern.
You post to form1, verify all data and store it. If the data is ok, you redirect to form2. If the data is wrong, you just show form1 again.
Redirecting is done by a header:
// Officially you'll need a full url in this header, but relative paths
// are accepted by all browsers.
header('Location: form2.php');
Save already posted fields in hidden input fields, but don't forget to validate them every time user submits another step of the form as the user may change hidden inputs in source code.
<input type="hidden" name"some_name" value="submitted_value"/>
There are several ways handling the submitted data while jumping between steps.
You will find your reasons for /against writing data to session, database, whatever... after each step or not.
I did following approach:
The form includes always a complete set of input elements, but on page #1 the step-2-elements are hidden ... and other way round.
I built a 6-step-wizard this way. One large template, some JS /Ajax for validating input, additional hidden inputs that hold current step-ID and PHP deciding, which fields to show or hide.
The benfit in my opinion: Data can easily be saved completely, as soon as input is alright and complete. No garbage handling, if users abort after step 1.
I would store it all in a session array (or sub array)
a really rough example where I'm saving all the form names to an array (to be checked later of course):
<?
foreach($_POST as $k => $v){
$session['register'][$k]=$v;}
?>
I am wanting to submit a form to different places based on selections made in the form. I had originally been planning to to send all to a central file/location and have it determine where to go next. However, I would like to do without this extra step if I could.
If the user wants to create/edit/delete elements go to page 1.
If the user wants to group/attach elements go to page 3.
I am trying to write a form builder. You can create/edit/delete forms, questions, and answers. I have everything for creating, editing, and deleting done. Those functions are performed without leaving the page, but now I am looking to assign answers to specific questions. The questions page and the answers page are separate. I am wanting to select a group of answers and submit an array of answer Ids (selected check boxes) to the question page where those Ids will then be assigned to a question. So basically the create, edit, and delete functions are on without leaving the page, but the assign function would be performed on a different page.
if(empty($delRowID) || empty(updateRowID) || empty($groupRows)) {
qInsert();
}else{
if(!empty($delRowID)) qDelete($delRowID);
if(!empty(updateRowID)) qUpdate($updateRowID);
if(!empty($groupRows)) {
submit $groupRows to Question.php;
}
}
No, a form has only one action.
But you have options:
Javascript
However, you may change the action attribute with javascript:
<input type="submit" value="Edit" onclick="editform();return true;">
<input type="submit" value="Delete" onclick="deleteform();return true;">
together with a little javascript:
function editform() {
document.myform.action = '/edit';
}
function deleteform() {
document.myform.action = '/delete';
}
See also
How to set form action through JavaScript?
Different form ACTION depending on button pressed
jquery, changing form action
Multiple forms
If javascript is not an option for you, you may consider multiple forms in your page.
Multiple forms = multiple actions
No problems with javascript disabled clients, and standards compliant.
Multiple submit buttons - server side
Or you may handle the distinction of editing or deleting on the server side. No javascript needed.
Add multiple submit buttons to your form and give them the same name but a different value:
<input type="submit" name="btSubmit" value="Edit">
<input type="submit" name="btSubmit" value="Delete">
You then can retrieve the value of the button which has been clicked. In php, the following should do the job:
$_POST['btSubmit']
See http://www.chami.com/tips/internet/042599I.html for an example with classic asp.
It is possible using JavaScript, but it's not recommended because some people turn JS off by default because of trojans and noisy behavior of some sites. It is considered polite to have your site working both with JS enabled and disabled.
Actually you don't need many form actions because every operation can be done using branching in the single form handler script.
Here is the very simple CRUD application example, performing displaying, editing, adding - all in one body and utilizing templates:
index.php
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
form.php
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
list.php
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
Just send them to a central location and use logic to send them somewhere else depending on what they selected.
eg:
<?php
switch($_POST['choice']) {
case 'edit':
$page = 'edit.php';
break;
case 'group':
$page = 'group.php';
break;
}
header("Location: " . $page);
(obviously needs some input filtering and default values)
EDIT: as pointed out by Col. Shrapnel below, using header() for this is pretty pointless as it'll then wipe out your $_POST array - use include() instead, but be careful to only allow your own files and never let the user name the file which will be included (eg using a form field value to pick the included file).
No, you can't have multiple actions just in the html, but you can use javascript to switch up the action depending on what button is hit.
I would do something like this (in pseudo-mootools)
<form action='default.php'>
... form elements ...
<button onclick='editButtonClick()' value='edit'/>
<button onclick='deleteButtonClick()' value='delete'/>
</form>
function editButtonClick() {
$('form').action = 'editaction.php';
$('form').submit();
}
function deleteButtonClick) {
$('form').action = 'deleteaction.php';
$('form').submit();
}
No, it can't (at least not without depending on JavaScript).
Submit to one URI, and have a dispatch routine pass the data off to different functions depending on which radio button (or whatever) is selected.
If I was looking at doing this I would pass a vaule of what you want doing by POST.
Then check that value against a set of functions and each function will do a different thing based on it selection
<input type="submit" value="Add" onclick="submitForm(this,'add')" />
<input type="submit" value="Update" onclick="submitForm(this,'update')" />
<input type="submit" value="Delete" onclick="submitForm(this,'delete')" />
var submitForm = function(context,uri)
{
form = contenxt.parent; //Go back to the form
form.action = uri; // Set the action
form.submit(); //Submit the form;
}
Java script is the best way to handle this, there's not really much alternative unless you create 3 sole forms.
Post your form to a central formhandler script. On that page just use simple logic (using php in this instance) to redirect the user to the specific page you want
on Submit page you can call CURL and give all Get or post variables to that url.