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
}
Related
I'm working in PHP to build a form. I know how to display the form and then take submitted values from the $_POST variable, and I know how to validate those variables and display a "Thank You" or an "Error" page depending on the input.
What I don't know how to do, though, is create a client-side-like system wherein despite having my users hit a "back" button a separate screen I can then take the information I gathered from the first submission and display dynamic error messages like "Please provide a valid email address" or "First name is a required field" next to the fields that were entered incorrectly. I'd also like to retrieve any previously submitted data that was valid and have it populate in the form so users don't get frustrated by losing everything they entered.
What is the right approach to accomplishing something like this in PHP? I originally thought if I could pass back an array of error messages with an input type="hidden" tag I could then pull my values and display messages dynamically with PHP, but I keep getting stuck in that approach.
You could add the errors a php session, but this creates issues for users who have multiple browser tabs open.
My preferred method is to have the form submit to the same page and put the errors directly on that page so the user does not have to click the back button. That way you can highlight the fields directly in the form (make the background or outline red or something similar.)
<input type="text"
<?php (empty($_POST['field']?'style="backgroung-color: red;"':''))?>
name="field" value="<?php echo $_POST['field']?>" />
You can put <input type="text" name="field" value="<?php echo $_POST['field']?>" /> to get the old value.
Because the web is, by definition, stateless, there is no really good way to track what the user does when they hit the back button. There are hacks that work using a hidden iframe, but that is way more trouble that what you are looking for.
Don't mix client logic with server logic. The exact same script can output the form and take it's input. In case input successfully validates, it goes on. If not, it will display the form again, this time with error messages and the already-entered data.
Next time the user submits the form, validation starts again until it passes successfully.
So you extend the form with input values and error messages in the first place, but you only display them if flagged/set.
This can be done just with additional variables next to $_POST - or if you like it - by using a complete form abstraction from a framework, like zend framework (which might be overhead for what you like to do) or just with a library/component like the popular HTML_QuickForm2.
Edit:
This is some very bare code to demonstrate the overall methodology, if you use a library it is much nicer (and you don't have to code it instead you can concentrate on the actual form like the definition on top). This code is more for reading and understanding the flow than for using, I quickly typed it so it (most certainly has) syntax errors and it's not feature complete for a full blown form. This one has only one email field and is even missing the submit button:
/* setup the request */
$request->isSubmit = isset($_POST['submit']);
/* define the form */
$form->fields = array
(
'email' => array
(
'validate' => function($value) {return filter_var($value, FILTER_VALIDATE_EMAIL);},
'output' => function($value, $name) {return sprintf('<input type="text" value="%s" id="%s">', htmlspecialchars($value), htmlspecialchars($name)},
'default' => 'info#example.com',
),
);
/**
* Import form data from post request
*
* #return array data with keys as field names and values as the input strings
* or default form values.
*/
function get_form_post_data($form, $request)
{
$data = array();
foreach($form->fields as $name => $field)
{
$data[$name] = $field->default;
if ($request->isSubmit && isset($_POST[$name]))
{
$data[$name] = $_POST[$name];
}
}
return $data;
}
/**
* Validate form data
*/
function validate_form_data($form, $data)
{
foreach($form->fields as $name => $field)
{
$value = $data[$name];
$valid = $field['validate']($value);
if (!$valid)
{
$form->errors[$name] = true;
}
}
}
function display_form($form, $data)
{
foreach($form->fields as $name => $field)
{
$value = isset($data[$name]) ? $data[$name] : '';
$hasError = isset($form->errors[$name]);
$input = $field['output']($name, $value);
$mask = '%s';
if ($hasError)
{
$mask = '<div class="error"><div class="message">Please Check:</div>%s</div>';
}
printf($mask, $input);
}
}
// give it a run:
# populate form with default values -or- with submitted values:
$form->data = get_form_post_data($form, $request);
# validate form if there is actually a submit:
if ($request->isSubmit)
{
validate_form_data($form, $form->data);
}
# finally display the form (that can be within your HTML/template part), works like echo:
display_form($form, $form->data)
Use the form to submit to the same page, and if the form validates, use a header to redirect the user into the thank you page.
header("Location: thank-you.php");
If the form fails validation, you could easily display all the errors on the same page.
i have 3 pages
Page1.php,page2.php,page3.php
In page1.php, i have some hidden values, for example 'name'
After the submission of page1.php, it will go to page2.
Then after some process in page2.php, it should need to automatically submit to page3.php(where page3.php is in another sever)
Finally,when i print the $_POST variables in page3.php, i need to get the variable 'name'
you could stick it in the session
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
or you could pass them in hidden vars on page2.php if it has a form...
You will want to look into sessions.
If you need them in POST, try this:
$display = "";
$saveFields = array('one', 'two'); // whitelist of fields to add to the form hidden
foreach ($_POST as $key => $val) {
if (!empty($val) && in_array($key, $saveFields))
$display .= '<input type="hidden" name="'.$key.'" value="'.$val.'" />';
}
echo $display;
Should get you where you want to go. The whitelist just ensure's that random stuff is not injected that does not need to be.
(1) Option is to add hidden input on page2 too.
(2) Option is to set the value from page1's name into session and use it on page3
There are several solutions:
PHP sessions
cookies
passing arguments as GET/POST parameters
storing data in database
In simple cases passing arguments as GET parameter page2.php?name=... or using hidden form field is the best solution
This seems straightforward to me, page one has a hidden value called name. Page 2 should retrieve the post $_POST['name'] and print it on page 2 as a hidden field. Once you post it to Page 3 you can retrieve it the same way $_POST['name'].
Realistically if the data is exactly the same and is being carried all the way to page 3, why do you even need it? Can you not just declare it on page 3?
Okay, the way I read this is that on your first page you have a UI with a form. The form is then submitted for processing to page 2. After processing is done, you want to redirect, if you will, the user to another site (or server, doesn't necessarily have to make a difference).
If I got that right, here is what you should do; instead of using the header(); function (php), print an empty page with a hidden form with all of the details you want to send over and use javascript to emulate the user 'submitting' the form.
< div style="display: none;">
< form action="https://mywebpage.com/myscript.php" method=POST>
< input type=hidden name="key_1" value="value_1">
< input type=hidden name="key_2" value="value_2">
< input type=hidden name="key_3" value="value_3">
< input type=submit id="formButton" style="visibility: hidden; ">
< script language="javascript">
document.getElementById("formButton").click()
< /form>
< /div>
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've got the following php code printing out the contents of a SQL table.
$query="select * from TABLE";
$rt=mysql_query($query);
echo mysql_error();
mysql_close();
?>
<i>Name, Message, Type, Lat, Lng, File </i><br/><br/>
<?php
while($nt=mysql_fetch_array($rt)){
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file]";
}
}
?>
How would I implement a button so for each "row" if the button is clicked on that row it'll submit the information of that row to another php file?
I want it looking something like...
details details2 details3 BUTTON
details4 details5 details6 BUTTON
details7 details8 details9 BUTTON
details10 details11 details12 BUTTON
Where if BUTTON was hit on row 1 details1,2,3 would be sent to a php file, on row 2 detals 4,5,6 would be sent etc. How would I do this?
Thanks.
it's going to be something like that, depending on the data you need to send:
while($nt = mysql_fetch_array($rt)) {
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file] ".'send request<br/>';
}
}
You can either use GET method and send a query string to the second php page and receive the variables there, like
next.php?variable1=value1&variable2=value2&...
or use POST method by making a hidden form for each row and assign a hidden field for each variable you want to send.
<form method="post" action"next.php">
<input type="hidden" name="variable1" value="value1" />
<input type="hidden" name="variable2" value="value2" />
.
.
.
</form>
or instead of sending all the values, just send the row ID (if any) using any of these two methods and run another query in next.php to get the information you need from database.
Instead of submitting the entire data, just send the ID and fetch the results from the database in the other script. If you want to have an input button, you can do
<form action="/other-script.php" method="GET">
<?php printf('<input type="submit" name="id" value="%s" />', $nt["id"]); ?>
</form>
but you could also just add a link, e.g.
printf('Submit ID', $nt["id"]);
If you really want to send the entire row values over again, you have to make them into form inputs. In that case, I'd send them via POST though.
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.