HTML form: action clarification - php

Hello I am currently making a registration page,
I'm new to php, and was wondering if this would work when I use the action part in form
<form method="post" id="formArea" action="action.php">
action.php is a file that contains
redirect.html
<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>
would this work? or is there a way where I can have both in the action section without the need for having to make a new file?

You Could Just Do This From The Form. If This is what your looking for:
<form method="post" id="formArea" action="<?PHP $_SERVER['PHP_SELF'];?>">
//this will make the form post to same page as the form
if your wanting to send this to both you can save the $_POST Data In A Variable and Use It Later.
EX:
<?PHP
//your form submit code might look something like this same file as your form
if(isset($_POST['submit']))
{
foreach($_POST as $key -> $value)
{
//echo or show your values or store your values in database or w/e
$_SESSION['post'][$key] = $value;
//this will make a session variable to be used again later each session array is marked with post identified by $key and stored a $value
}
//you can call your other page here this will only run after this page runs and loads your information above and then redirect with a session variable.
header("Location: redirect.html");
}
else
{
echo "<form method=\"post\" id=\"formArea\" action=\"".$_SERVER['PHP_SELF']."\">";
}
This Code Is Not Tested But It Would Work the redirect.html will process code from $_SESSION['post']

Related

I need to send an action and a variable to the url

This is the action in my form
action="/Classes/Controllers/DoctorController.php?action=editVC"
the action I am sending is ?action=editVC
I need to also send a variable I got from this block of code
<?php
if(isset($_GET['userID'])){
$currentUserID = $_GET['userID'];
}
?>
Given that they are all in the same file, and I want to send the variable $surrentUserID like this ?userID=$currentUserID in the url as well along with the action.
I have tried this way but it did not work
action="/Classes/Controllers/DoctorController.php?action=editVC&userID=$currentUserID"
It looks like you just need to invoke PHP and print the variable, so either in your HTML:
<form action="/Classes/Controllers/DoctorController.php?action=editVC&userID=<?php print $currentUserId; ?>">
Or you might prefer to concatenate the action in a string first like:
PHP:
<?php
$action = '/controllers/DoctorController.php?action=editVC&userID='.$currentUserId';
?>
HTML:
<form action="<?php print $action; ?>">...</form>

How to call php function on html form submit - in the same page

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.

PHP FORM navigation with Hidden values

I am developing a form in PHP. There are variables which are fix which will be displayed in the link of the web page. But some variable which are passed to other page are in hidden and are not fixed.
Eg.
http://editform.php?var1=23&var2=34 will have hidden variables hidvar=23
http://editform.php?var1=23 this will not have any hidden variable and also var2 is also not there
I have checked for variable in link with isset function.
if(isset($_GET['var2']))
now how to get all the variables values in another page with all combination of hidden variables and variable in Link.
I am further adding code which let you get the Idea what I need. Below web page is saved as webform.php
<?PHP
if(isset($_GET['YID']))
{ $YRID=$_GET["YID"]; }
else
{ $YRID=0; echo "Variable Missing. Program terminated."; }
?>
// GET THE VALUE OF $PASS;
//GET THE VALUE OF SESSIONID;
//GET THE VALUE OF YID.
<form action="WEBFORM.php?PASS=<?PHP echo $PASS;?>" name="FORM1" METHOD="POST">
<?php
//statement which do some operation using $YRID;
?>
<input type="hidden" name="SESSIONID" VALUE="<?PHP echo $SESID; ?>" />
</FORM>
while (list($key, $value) = each($_REQUEST))
{
echo ($key.' '.$value);
}
Where $key is the variable name, $value is variable value
I have tried the below code
isset($_POST['SUBMIT'])
if form is submitted then above code will check the variable which are hidden.
for checking the hidden variables and for the variable in link i have checked using below code
if(isset($_GET['YID']))
if form is not yet submitted then above code will check the variable.

Possible to manipulate $_POST variable in php script and express it in another php script?

I've been trying to do form validation without using the url. So I thought that I would create a hidden field in my form and send it over to my validation php script. What I was hoping I would be able to do is set what ever errors there are in the form to this hidden field and return it. However once I get out of the scope it destroys whatever I set. I thought $_POST had global scope? Maybe I declared I set the hidden field wrong? I have placed the code below.
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/databaseConnect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/config/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/users.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/poles/models/userDetails.php';
//get the refering url to be used to redirect
$refUrl = $_SERVER['HTTP_REFERER'];
if(isset($_POST['register'])){
//declare a temp error array
$tempError;
//check if the form is empty
if(empty($_POST['Email'])&&empty($_POST['Email Confirmation'])&&empty($_POST['Password'])&&empty($_POST['Password Confirmation'])
&&empty($_POST['Stage Name'])&&empty($_POST['Main Club'])){
$tempError = 'Please fill in the form.';
}else{
//set variables
}
if(!empty($tempError)){
//start a session to declare session errors
$_POST['errors'] = $tempError;
//redirect back to referring url
header('Location:'.$refUrl);
exit();
}else{
//log user in and redirect to member home page
}
}
Basic form (I excluded the input field as it would be really long)
<div class="col-md-6 well">
<span class="jsError"></span><?php if(isset($_POST['errors'])){ $errors = $_POST['errors']; } if(!empty($errors)){ echo '<p class="alert alert-danger text-center">'.$errors.'</p>'; } ?>
<form class="form-horizontal" role="form" method="post" action="controllers/registrationController.php" id="registration">
<input type="hidden" name="errors" value="<?php if(isset($_POST['errors'])){echo $_POST['errors']; } ?>">
</form>
I looked into using the $_SESSION variable method too but the stuff I found was either a bit complicated or it involved me starting a whole bunch of sessions everywhere (would make my code messy in my opinion).
$_POST is populated from the contents of the data passed by the browser to the server. When you send a Location header it causes the browser to load a new page, but since it will have no form data, nothing will be passed.
If you need to pass data from page to page then $_SESSION is the way to go. All that is required is a session_start() at the top of the pages that need access, and you can store your $_POST data like this:
$_SESSION['postdata'] = $_POST;
Retrieving it becomes
$email = $_SESSION['post']['Email'];
The alternative is to echo the data as a hidden <input> in a new form, but that will require a new form to be submitted and I get the feeling you want something seamless.
Note also that $_SERVER['HTTP_REFERER'] is not guaranteed to be accurate, or even present. You shouldn't rely on this for production code. It might work for you with your browser in your test set-up, but that's no guarantee it'll work for other browsers. Find another way.
You can achieve this by using javascript instead of a redirect, but the only way to pass data through a redirect is via the URL, the session, or cookies.
$_POST['errors'] = $tempError;
//redirect back to referring url
?>
<html><head><title></title></head><body>
<form id="temp_form">
<?php
foreach($_POST as $k=>$v) {
?><input type="hidden" name="<?php echo htmlentities($k); ?>" value="<?php echo htmlentities($v); ?>" /><?php
}
?>
</form>
<script type="text/javascript">
setTimeout(function() { document.getElementById('temp_form').submit(); },100);
</script>
</body>
</html>
<?php
die();

session gets lost after form submit

When a user links to link it redirects to edit.php - here's an example: www.cars.com/edit.php?id=23
In edit.php, I use _GET to store the value in a session. The value is stored in $_session['user'] but when the form on the same page is submitted echo $_session['user'] displays nothing - how can I make it display the value?.
<?php
session_start();
$_session['user']=$_GET['id']; // I use _GET to store the value in session
if( isset($_POST['submit'])) {
echo $_session['user'];
}
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="formI2D" enctype="multipart/form-data" id="formI2D" />
It's because you're redeclaring your $_SESSION['user'] even when it's a POST (I think).
You can fix this by adding ?id=$_GET['id'] in you form's action, or by wrapping your $_SESSION initialisation like that:
if (isset($_GET['id'])) {
$_SESSION['user']=$_GET['id'];
}
Also, you should use uppercase for php global arrays ($_POST, $_COOKIE, $_SESSION etc)

Categories