Here is my scenario, I am creating a form with codeigniter, I understand how to populate the fields with models and such. I have the layout of the form. It is now running from my index function. I want to store all the data given to that form and access them in a postdata array with each index being the name of the value. Please help. CodeIgniter, PHP
you create the form
echo form_open('mycontroller/mymethod');
// rest of form functions
or <form name="myform" method="post" action="<?php echo site_url('mycontroler/mymethod');?>" > // rest of html form
then, in Mycontroller:
function mymethod()
{
$postarray = $this->input->post();
// you can pass it to a model to do the elaboration , see below
$this->myloadedmodel->elaborate_form($postarray)
}
Model:
function elaborate_form($postarray)
{
foreach($postarray as $field)
{
\\ do your stuff
}
}
If you want XSS filtering you can pass a TRUE as second parameter in the $this->input->post() call. Check user guide on input library
See code igniter's input class
One exemple of how to form your code would be:
public function add_something()
{
if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') { // if the form was submitted
$form = $this->input->post();
// <input name="field1" value="value1 ... => $form['field1'] = 'value1'
// you should do some checks here on the fields to make sure they each fits what you were expecting (validation, filtering ...)
// deal with your $form array, for exemple insert the content in the database
if ($it_worked) {
// redirect to the next page, so that F5/reload won't cause a resubmit
header('Location: next.php');
exit; // make sure it stops here
}
// something went wrong, add whatever you need to your view so they can display the error status on the form
}
// display the form
}
This way your form will be displayed and if submitted its content will be processed, if an error occurs you will be able to keep the submitted values to pre-enter them in the form, display an error message etc ... And if it works the user is redirected to that he can reload the page safely without submitting multiple times.
Related
I wonder how to validate fields in html form using PHP so that when I click the button "submit", it won't advance to another page before all field is valid?
//this checks if the submit button or the name you've given in the submit button is set
if(isset($_POST['submit'])){
//getting the html element name to the variable $name
$name=$_POST['name'];
//do your validation here
if($name==''){// this checks if the $name field is null or empty
// error alert user
}else{
// do your required tasks here or simply add an else if
// and check for another validation
}
}
Use an if statement on the server side, something along the lines of...
if($POST['txt'] != ''){
// validation successful, redirect user
}
else
{
// validation failed, alert user
}
I want to redirect to a page after executing a php function and also submit a html form with the methode POST, at once.
I found many solutions with GET but I want to handle this with POST.
You can use cUrl to send POST data you want, then make the redirect.
Look on the net for: "php curl".
Make your form action point to the php document where you want to execute your function and then in the end place this header("location: your_location_file.php");
Step one - submit form to functions.php
Step two - do what ever you need to do with the submited data
Step three - Redirect
Example:
<form method="post" action="functions.php">
...
</form>
functions.php
<?php
...
all your code
...
header("location: your_location_file.php");
?>
Javascript can help if you don't want to rely on curl. Had this laying around. Pass in $_POST or an array of the data you want posted. Add error/parameter checking.
function http_post_redirect($url='', $data=array(), $doc=true) {
$data = json_encode($data);
if($doc) { echo "<html><head></head><body>"; }
echo "
<script type='text/javascript'>
var data = eval('(' + '$data' + ')');
var jsForm = document.createElement('form');
jsForm.method = 'post';
jsForm.action = '$url';
for (var name in data) {
var jsInput = document.createElement('input');
jsInput.setAttribute('type', 'hidden');
jsInput.setAttribute('name', name);
jsInput.setAttribute('value', data[name]);
jsForm.appendChild(jsInput);
}
document.body.appendChild(jsForm);
jsForm.submit();
</script>";
if($doc) { echo "</body></html>"; }
exit;
}
You could use a session to hold the POST data.
I am currently using code like below. On my first page load, the $_POST data is checked. If it contains certain values already in the database, then it redirects to a page for those values.
// This could be part of the same script as below, or a different script.
session_start();
if($_POST['my_value'] && valueExistsInMyDb($_POST['my_value']) ) { // check my db to see if this is an existing value
$id = getIdOfMyValue($_POST['my_value']); // e.g. '4'
$_SESSION['POST'] = $_POST; // take ALL post data and save it in the session variable
header("location: your.php?myvalue=" . $id); // redirect to bookmarkable target page where $_GET variable matches what was posted.
exit(); // ensure no other code is executed in this script after header is issued.
}
Then your other file (or maybe even the same file) could do this:
// your.php?myvalue=4
if(isset($_SESSION) && array_key_exists('POST',$_SESSION)) {
$_POST = $_SESSION['POST']; // creates or overwrites your $_POST array with data from the session. The rest of your script won't be able to tell that it's not a real $_POST, which may or may not be what you want.
unset($_SESSION['POST']); // you probably want to remove the data from the session.
}
// now your myvalue=4 is stored in GET, and you can handle the rest of the POST data as you like
I don't know if that is the best solution, but so far it seems to be working for me so far. I only just wrote the code a few days ago and haven't tested all aspects yet.
Another option is to use HTML5 to change the address bar. No redirect needed. But the downside is that only "modern Webkit browsers" can use it, apparently.
I'm having a problem with a HTML form (name, e-mail, subject, message), I can't validate the form if it was completed correct or not. I want to call a javascript function when the form is submitted and alert if a field wasn't completed correct.
My problem is with the submit button, because my boss said that I must use he's own php function to insert a submit button. The php function looke like:
function normal_button($text, $width, $param = '', $class = 'button-blue')
{
$content = '<div class="'.$class.'" style="width:'.$width.'px;" '.$param.'>'.$text.'</div>';
return $content;
}
and how I call the function:
echo normal_button('Send it', '100', 'onclick="document.getElementById(\'emailForm\').submit();" ');
I tried to call the js function declaring the onSubmit="return checkForm(this)" in the <form action='email.php' method='post'> HTML form, but I can't "catch" the submit. Also I tried to catch it with jquery, $(document).ready(function() { $('.normal_button').click(function() { }); ); but I can't return false if a field wasn't completed correct.
I must use he's PHP function to insert the submit button, but how can I "catch" the fields, how can I validate them? Any suggestions? Thank you !
First of all, set ID for that form and for sbmit DIV button.
<form action='email.php' method='post' id='mailForm'>
and
echo normal_button('Send it', '100', 'id="mailFormSubmit"');
then do check with jQuery:
$('#mailFormSubmit').click(function(){
// fields check code goes here
....
// if all fields are OK, then submit form
$('#mailForm').submit();
});
I have a multi-page form. Visit page 1, page 2 and then page 3. Push refresh (f5) and the form goes back to page 2.
This is with drupal-6. The problem looks similar to this http://drupal.org/node/1060290.
Digging into the problem, via the form_cache database table. Both page 1 and 2 data appear in there. In the php debugger it looks as though a new form_id has been created. ie. storage_form-1add3819cbea88139679819935a69686 is the key in the database cache table and form-bcf9556f57f5352a57dfbba4c2120ee7 is the 'form_id' on refresh.
What does my form code look like?
Main form function:
function myform_online(&$form_state) {
// $form_state['storage']['step'] keeps track of what page we're on.
// start at step 1 if no storage has been set
if (!isset($form_state['storage']['step'])) {
$form_state['storage']['step'] = 1;
}
// If we are saving the form data we should submit rather than display the details.
// At least look at saving the step.
// Don't lose our old data when returning to a page with data already typed in.
$default_values = array();
if (isset($form_state['storage']['values'][$form_state['storage']['step']])) {
$default_values = $form_state['storage']['values'][$form_state['storage']['step']];
}
switch ($form_state['storage']['step']) {
case 1:
// Your Details
module_load_include('inc', 'join_online', 'includes/step1');
And we handle submit:
function join_online_submit($form, &$form_state) {
//Save the values for the current step into the storage array.
//dsm($form_state);
$form_state['storage']['values'][$form_state['storage']['step']] = $form_state['values'];
# ahah - bail.
if ($form_state['ahah_submission']) {
return;
}
// How do we work out if this was a refresh? It currently does start with 1 and think that the step is #2.
//Check the button that was clicked and change the step.
if ($form_state['clicked_button']['#id'] == 'edit-previous') {
$form_state['storage']['step']--;
} elseif ($form_state['clicked_button']['#id'] == 'edit-next') {
$form_state['storage']['step']++;
} elseif ($form_state['clicked_button']['#id'] == 'edit-finish') {
//You should store the values from the form in the database here.
//We must do this or the form will rebuild instead of refreshing.
unset($form_state['storage']);
//Go to this page after completing the form.
$form_state['redirect'] = 'join_online/form/thank-you';
}
}
If you use $form_state['rebuild'] = TRUE in _submit function the state of the form is saved and can be used for default values.
Check this example:
http://www.ferolen.com/blog/how-to-create-multistep-form-in-drupal-6-tutorial/
I have a form containing tabular data, with each row having a checkbox with the same name so that it gets passed via POST as an array to a PHP page. Everything work fine, but I have an issue relating to when none of the items on the page are selected - this is a special case that I need to handle in a specific way, but I am trying to figure out how to determine the best way to tell when this condition occurs, as when it does the $_POST array is completely empty.
Any strategies to help in determining when an empty set of data has been POSTed to a page in PHP?
Use the empty function
if( empty($_POST) ) {
//do empty $_POST stuff here
}
Add a hidden input field to the page with a known value. This field will always be passed in with the POST data, therefore you will know that the user landed via form submission rather than direct URL. It's as simple as:-
<input type='hidden' name='posted' value='true'>
You can accomplish this a few different ways.
//Method 1
if($_POST) {
//Do Stuff
}
//Method 2
if(!empty($_POST)) {
//Do Stuff
}
//Method 3 - For detecting if a form was submitted
<input type="submit" name="submit" />
if(sizeof($_POST)>1) {
//Do Stuff
}
Method 2 will fail if your value is 0, for a checkbox you need not worry though.
Method 3 relies on you giving your submit button a name, so it is at least submitted when nothing is checked. Then you can see if sizeof() returns more than 1 to see if anything was checked.
DEMO: http://wecodesign.com/demos/stackoverflow-7424062.php
I think you've answered your own question. If the $_POST array is empty then there are no checked checkboxes.
<form>
<input type="text" name="user" value="" />
<input type="submit" name="post" value="Save" />
</form>
//php
if (isset($_POST['post']))
{
//code here
}
if ( !empty( $_POST["field"] ) ) {
// Field sent
} else {
// Field empty
}
(count($_POST) == 0) //returns boolean
or do you mean when the form is posted but no information is entered?
Post data is available when a form is submitted. Given the following:
if($_POST)
{
// Bar
}
// Foo
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed and then Foo.
Given the following:
if ($_POST)
{
// Bar
}
else
{
// Foo
}
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed.
As for your other question, checking for empty or appropriate data is basic server-side form validation. If you use a library that can be as simple as:
if ($_POST)
{
$form_helper = new FormHelper();
$form_helper->validate($_POST["email"], "email");
$form_helper->validate($_POST["password"], "password");
if (! $form_helper->notifications())
{
// Bar
}
}
For your specific case (and without a library) it might be:
if ($_POST)
{
if (empty($_POST["checklist"])
{
// Delete all entries.
}
else
{
// Do something else.
}
// Foo
}
This will check if any form values have been entered - assuming default input value = ''
$post = array_filter($_POST,'strlen'); //filter all empty values
//if html input submit button has NO name value
if (sizeof($post)):
//Do stuff
endif;
// OR if html input submit button HAS a name value
if (sizeof($post) > 1):
//Do stuff
endif;
You could use a callback function if exact filtering was required
$post = array_filter($_POST,function ($k){ return $k != '' || $k != 'my default value' || *some other condition etc etc* ; });