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.
Related
I'm having trouble adding the value of type="button" form elements to a mySql database, and I'm wondering if I'm missing something.
Edit - It doesn't look like the information for that element is being passed from the html to the php because it's not echoing a value. My only problem is with this one element and the rest of the form is being submitted properly.
I'm using this for an online quiz which builds a user profile based upon images they've selected, and am setting the images as background images for the button elements, and I'm trying to do this in straight html (as opposed to using javascript together with radio buttons or check boxes).
<input type="button" name="quiz_start" value="jeans" style="background: url(files/start1.jpg) no-repeat; width:54px;height:140px; cursor:pointer; border:none; color: transparent; font-size : 0">
I've simplified the php code for purposes of asking the question (including specifying the user id and limiting it to only one field). I've also included the full code below.
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('$user_id','$_POST[quiz_start]')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>
The full query is:
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.($value).'\',';
}
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$fieldlist.=', user_id';
$vallist.=','.$user_id;
$setlist='';
foreach ($_POST as $key=>$value){
$setlist.=$key .'=\''.$value.'\',';
}
$setlist=substr($setlist, 0, -1);
$result = mysql_query('UPDATE style SET '.$setlist.' WHERE user_id='.$user_id);
if (mysql_affected_rows()==0) {
$result = mysql_query('INSERT INTO style ('.$fieldlist.') VALUES ('.$vallist.')');
}
header("location: page2.html");
exit();
?>
Seeing that you are unable to echo $_POST['quiz_start'] that means your value is not actually set. This is because when you use a class button as in <input type='button'> your form is not actually submitted like <input type='submit'>
One solution would be to change your button to an actual submit and format that... or you need to call a javascript function with an onClick from your button as in:
<input type="button" onClick="myfunction()">
For reference to what I am talking about look at this post.
If as you say the rest of the form values are submitting fine but just the button value is not working you have a few different possible solutions depending on your preference.
Use a select field or checkbox for people to select a type in which you can pass your data.
Submit your form in javascript with <input type="button" onClick="myfunction()"> then running your update query in javascript.
Finally if you still want to run your query in PHP you can run a javascript function to make an AJAX call to return JSON information in which you can define a php variable after the page has loaded in which you can then plug into your update query.
Try this:
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('".$user_id."','".$_POST['quiz_start']."')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>
Since it seems that input type="button" can't capture the user's selection, I wanted to share a really simple way I figured out for doing this with radio buttons or check boxes using only html.
All you need to do is set the input element to style="display:none", and surround both the image and input element with a label tag so that users can click anywhere on the image to select the element :-)
<label for="quiz_start">
<img src="files/start1.jpg" />
<input style="display:none" type="radio" id="quiz_start" name="quiz_start" value="jeans">
</label>
I'm having trouble adding the value of type="button" form elements to a mySql database, and I'm wondering if I'm missing something.
Edit - It doesn't look like the information for that element is being passed from the html to the php because it's not echoing a value. My only problem is with this one element and the rest of the form is being submitted properly.
I'm using this for an online quiz which builds a user profile based upon images they've selected, and am setting the images as background images for the button elements, and I'm trying to do this in straight html (as opposed to using javascript together with radio buttons or check boxes).
<input type="button" name="quiz_start" value="jeans" style="background: url(files/start1.jpg) no-repeat; width:54px;height:140px; cursor:pointer; border:none; color: transparent; font-size : 0">
I've simplified the php code for purposes of asking the question (including specifying the user id and limiting it to only one field). I've also included the full code below.
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('$user_id','$_POST[quiz_start]')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>
The full query is:
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.($value).'\',';
}
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$fieldlist.=', user_id';
$vallist.=','.$user_id;
$setlist='';
foreach ($_POST as $key=>$value){
$setlist.=$key .'=\''.$value.'\',';
}
$setlist=substr($setlist, 0, -1);
$result = mysql_query('UPDATE style SET '.$setlist.' WHERE user_id='.$user_id);
if (mysql_affected_rows()==0) {
$result = mysql_query('INSERT INTO style ('.$fieldlist.') VALUES ('.$vallist.')');
}
header("location: page2.html");
exit();
?>
Seeing that you are unable to echo $_POST['quiz_start'] that means your value is not actually set. This is because when you use a class button as in <input type='button'> your form is not actually submitted like <input type='submit'>
One solution would be to change your button to an actual submit and format that... or you need to call a javascript function with an onClick from your button as in:
<input type="button" onClick="myfunction()">
For reference to what I am talking about look at this post.
If as you say the rest of the form values are submitting fine but just the button value is not working you have a few different possible solutions depending on your preference.
Use a select field or checkbox for people to select a type in which you can pass your data.
Submit your form in javascript with <input type="button" onClick="myfunction()"> then running your update query in javascript.
Finally if you still want to run your query in PHP you can run a javascript function to make an AJAX call to return JSON information in which you can define a php variable after the page has loaded in which you can then plug into your update query.
Try this:
<?php
//Start session & connect to database
$user_id = 3;
$qry = "INSERT INTO style(user_id, quiz_start) VALUES('".$user_id."','".$_POST['quiz_start']."')";
$result = #mysql_query($qry);
header("location: page2.html");
exit();
?>
Since it seems that input type="button" can't capture the user's selection, I wanted to share a really simple way I figured out for doing this with radio buttons or check boxes using only html.
All you need to do is set the input element to style="display:none", and surround both the image and input element with a label tag so that users can click anywhere on the image to select the element :-)
<label for="quiz_start">
<img src="files/start1.jpg" />
<input style="display:none" type="radio" id="quiz_start" name="quiz_start" value="jeans">
</label>
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 have a Zend Framework form that has two submit buttons
$changes = new Zend_Form_Element_Submit('save_changes');
$changes->setLabel('Save Changes');
$delete = new Zend_Form_Element_Submit('delete');
$delete->setLabel('Delete');
Which renders HTML like such:
<input type="submit" name="save_changes" id="user_save_changes" value="Save Changes" >
<input type="submit" name="delete" id="user_delete" value="Delete" >
In the controller, how do I determine which button the user pressed?
In your case you should just be able to check
if(isset($_POST['save_changes'])
// or
if(isset($_POST['delete'])
Since only the value of the clicked button will be submitted.
Usually you give both buttons the same name (e.g. action) and then set the
value to the action you want to perform. Unfortunately that doesn't work very well
with IE. Check this page for more information about different solutions for multiple
submit buttons.
Since you are using Zend I would recommend a more Zend-ish approach.
You can call elements directly by theirs names and Zend has a method for form buttons (buttons, reset, submits) called isChecked().
in your code it would be:
if ($form->save_changes->isChecked()) {
// Saving ...
else if ($form->delete->isChecked()) {
// Removing ...
Actually you can get this by:
if($this->getRequest()->getPost('save_changes'){
//Code here
}
if($this->getRequest()->getPost('delete'){
//Code here
}
The reason I made two if condition because you can't do if else because one you load that page even though you didn't click any submit button, the other condition will be executed.
Example:
if($this->getRequest()->getPost('save_changes'){
//once you load this will become true because you didn't click this
}else{
//once you load this page this will become true because you didn't click the save_changes submit button
}
True story.
$data = $this->getRequest()->getPost();
if (array_key_exists('save_changes', $data)) {
..
} else if (array_key_exists('delete', $data)) {
..
}
$formData = $this->getRequest()->getPost();
if($formData['submit']=='save_changes'){ // echo "save chanes" ; }
if($formData['submit']=='delete'){ // echo "delete";}
I’m usually Using input type submit eg: <input type=“submit” name=“assign” value=“Assign”/>
and using this is no problem for me but now I want to use button eg:<button type=“button” class=“button” id=“deleteb”><div>Assign Student</div></button>
but don’t know how to used it or call it to my controller.
this is my controller function
if($assign_student)//<input type="submit" name="assign" value="Assign"/>
{
if($maxMember->max_members > $countMember)
{
if($countMember+1 == 1)
{
$is_leader = 1;
}
else
{
$is_leader = $this->input->post('is_leader');
}
$student = array(
'user_id' => $this->input->post('student'),
'group_no' => $this->input->post('group'),
'is_leader' => $is_leader
);
$this->admin_db->save_group($student['group_no'],$student);
}
else
{
$data['max_error'] = "<p class='error'>Sorry, This group reached the maximum number of members!</p>";
}
}
If you want the button to submit the form you must have type="submit"
If you want the button to send a value, it's better to use a hidden input to send along additional information. Example:
<input type="hidden" name="assign" value="Assign" />
You can set a name and value to the <button>, but guess what?: In IE6, the actual html content of the button will be sent as the post data instead. It's one of my favorite bugs.
It's not very clear why you posted your controller code, but if you are checking for a "trigger" value before processing, like $this->input->post('assign'), you can check for the presence of any other of the form values instead, or the presence of any $_POST values, or as I mentioned: a hidden input.
If you press a submit-button, you are posting a form to some
script, in this case PHP.
if you submit the form, your browser sends the information
contained in the form to the receiving script.
eg, if you make a page with a form that contains:
You can check like this...
if (isset($_POST["deleteb"]))
{
//Do stuffs
}