Is this how AltoRouter GET POST method work? - php

I have been trying out this altorouter for weeks now. This is looks to be good router with not many working example either on the nets or the official site. You need to understand it somehow and get the job done.
I tried the basic GET and POST using the altorouter and do not know whether this is the right way of doing it.
Simple GET method in php
<html>
<head>
</head>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
The way I did it using AltoRouter
Index.php
<?php
require 'library/AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/AltRouter');
$router->map('GET','/', function() {require __DIR__ . '/catalog/controller/home.php';}, 'home');
$router->map('GET|POST','/aboutus/', function() {require __DIR__ . '/catalog/controller/aboutus.php';}, 'aboutus');
$router->map('GET|POST','/contactus/', function() {require __DIR__ . '/catalog/controller/contactus.php';}, 'contactus');
$router->map('GET|POST','/welcome/', function() {require __DIR__ . '/catalog/controller/welcome.php';}, 'welcome');
$match = $router->match();
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
contactus.php (Get Method)
<html>
<head>
</head>
<body>
<form action="../welcome/" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
welcome.php
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
For some odd reason this works but I feel this isn't right. Reason: Information sent with the GET method is visible to everyone, the variables are displayed in the URL, it is possible to bookmark the page.Where as the URL that I get after submitting the form is this
http://localhost/altrouter/contactus/
No variable displayed after submitting the form in the URL.
Now for the POST method, this one works you need to let me know is this how we are supposed to do it or not.
Index.php
same as the one posted above
aboutus.php (POST method used)
<html>
<head>
</head>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["first_name"];
$email = $_POST["email_address"];
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
}
?>
<form action="<?php $_SERVER["PHP_SELF"]?>" method="post">
Name: <input type="text" name="first_name">
<br><br>
E-mail: <input type="text" name="email_address">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
This works and the data posted is echo'ed out, URL after submitting
http://localhost/altrouter/aboutus/
Please let me know what is right and what is wrong.

I don't think I understand what you are asking... I do have some observations, though:
Information sent with the GET method is visible to everyone, the variables are displayed in the URL
Yes, that happens in HTTP method GET, the ?name=Joe&email=joe#example.com at the end of the url is called "query string". One of its differences with method POST is that the data is part of the url, so it's visible (alhtough don't trust that it is not visible otherwise) and as you say it can be bookmarked.
On GET vs POST, read about the usage of those methods and decide one for each route. I don't think it's good design, let alone easily maintainable, to have several methods mapped to a single controller. Take advantage of the router, map different methods, for instance:
$router->map('GET','/contactus', 'showContactForm');
$router->map('POST','/contactus', 'processContactForm');
Since you tag the question with "MVC", you could separate things further and have your controllers be just controllers which in turn call or generate views. Or, you can just use a full MVC framework, even a light one like Lumen, which manages routing, view templates, database connection, authentication and much more.
<form action="../welcome/" method="post">
From http://localhost/altrouter/contactus/ to http://localhost/altrouter/welcome/ the relative url can be just welcome. The .. means "go up a directory".
the URL that I get after submitting the form is this
http://localhost/altrouter/contactus/
I don't get why, if the form submitted successfully as you say, you should be in http://localhost/altrouter/welcome/
Avoid $_SERVER["PHP_SELF"]. It brings insecurities. A form with no action attribute will just submit to the same url. With method POST, you can, for the same url, handle both actions separately as I said earlier.

Related

Using multiple PHP files while avoiding redirect loop and resubmission

So I am pretty new to PHP, I have done and learnt lots of console based experience so I'm not a full beginner to programming. But I decided to learn how to database because its always fascinated me, and I've learnt the basic HTML and CSS and JS, and now basic PHP and SQL, but putting into action is getting weird on me.
I've figured out how to manipulate and make databases through PHP code and stuff like that, but they were all simple things and in one file, I am going for a bigger project and I need to put all the PHP's in separate files, this is the problem.
say my 'index.php' file is so:
<!DOCTYPE html>
<html>
<head>
<?php include 'other.php' ?> //Problem 1
</head>
<body>
<FORM method="POST" action="other.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
and my 'other.php' is :
<?php
$input = "";
if (isset ($_POST['subTest']))
{
$input = $_POST['textTest'];
//header("Location : index.php");
}
header("Location: index.php"); //Problem 2
?>
so my problems:
Problem 1, if I don't include the 'other.php' file, there is an error when I try print the: value = "print $input"
Problem 2, if I don't redirect with 'header', it obviously doesn't redirect and go back to the 'index.php' which I want to happen. BUT with it there, it causes a TOO_MANY_REDIRECT error. I found this is a problem caused by the include which can't be removed for Problem 1 reasons.
Problem 3, I found out I could move the 'header' function to where it is commented out, but then the value="..." doesn't stay on submit.
Problem 4, if I completely get rid of the 'header' redirect, and change the form's action to 'index.php', then I get the 'Confirm Form Resubmission' thing I want to avoid.
So I hope that is a mouthful someone understands and can help with, and thankyou in advanced.
include does what it sounds like, it includes the file into the parent, essentially the same as copy and pasting the content into it.
So to fix your problem, 1st change the forms action to index.php (so it posts to its self), and remove the redirect all together:
<?php include 'other.php' ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<FORM method="POST" action="index.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
other.php:
<?php
$input = "";
if (isset ($_POST['subTest'])){
$input = $_POST['textTest'];
}
Note that i also moved the include to the 1st line in index.php, before any html output.
This is not strictly required in this instance, but is a good practice, as you are unable to set headers (eg for a redirect) after the response body is sent to the output stream
EDIT
If you want to avoid form resubmits on refresh, then you are correct that you would need to submit to a seperate endpoint and redirect.
To do that you would need to pass the posted data back to the index file, as the redirect is a new (GET) request, so the post data is lost.
The two main ways to do that would be with SESSION or URL parameters.
I'll show how to do it with parameters:
Dont include the destination file:
<?php
//get value from url parameter, or set to empty string if parameter not present
$input = isset($_GET['input'])? $_GET['input'] : '';
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<FORM method="POST" action="other.php">
<INPUT type="text" name="textTest" value="<?php print $input; ?>">
<INPUT type="submit" name="subTest" value="TEST" >
</FORM>
</body>
</html>
Then append the required data to the redirect url as parameters
other.php:
<?php
$input = "";
if (isset ($_POST['subTest'])){
$input = $_POST['textTest'];
header("Location: index.php?" . http_build_query(['input'=>$input]));
die(); //always stop execution after redirect
}
//if post data not sent, something went wrong, so set $input parameter to error message
header("Location: index.php?" . http_build_query(['input'=>'No Data posted']));
die(); //always stop execution after redirect
In other.php at the last line try require-ing the index.php instead of redirrecting.
Also remove the inclusion of other.php in index.php .
$input = "";
if (isset ($_POST['subTest']))
{
$input = $_POST['textTest'];
}
require_once 'index.php';
?>

PHP post method

my code for welcome.php is as beow:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
and the form :
<html>
<body>
<form action="welcome_get.php" method="get">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
It should give the output my name and email id when I fill the form with my name and emailid .
but it is giving me the below error running the php file
Welcome
( ! ) Notice: Undefined index: name in C:\wamp\www\PHP Learning\welcome.php on line 4
Call Stack
# Time Memory Function Location
1 0.0000 236440 {main}( ) ..\welcome.php:0
Your email address is:
( ! ) Notice: Undefined index: email in C:\wamp\www\PHP Learning\welcome.php on line 5
Call Stack
# Time Memory Function Location
1 0.0000 236440 {main}( ) ..\welcome.php:0
corresponding to that when I run html file which is supposed to give me the correct out, it only shows the
in the address bar I get this:
LH/PHP%20Learning/welcome_get.php?name=shailesh+kumar&email=shailblack%40gmail.com
Not Found///
The requested URL /PHP Learning/welcome_get.php was not found on this server.
Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 80
Please suggest where i m missing to execute the post method.
You are accessing POST variables directly but your form is submitted with the GET method.
By the way, you shouldn't ever use globals in the way that you have done in your example.
change your php file to
<html>
<body>
Welcome <?php echo isset($_POST["name"]) ? $_POST["name"] : ''; ?><br>
Your email address is: <?php echo isset($_POST["email"]) ? $_POST["email"] : ''; ?>
</body>
</html>
When script is executed for the 1st time, the $_POST variable is empty array. Thats why you have got errors.
Then as others told you - change your method to post.
You method you use is get.
You must change that to post.
For more information, you can read this article.
you're using <form action="welcome_get.php" method="get"> to perform a GET request, but use $_POST['name'] to get that value.
so try the example below
welcome.php
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
and the form:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
Your script is requesting the URL welcome_get.php but you named your file welcome.php - you need to change one of them. Your code is currently searching for a file that doesn't exist.
If you want to post use method="POST" not method="get".
When you load the page your script looks for $_POST['name'] and $_POST['email']. What happens when you don't post any data? Well as you've seen you get errors.
Check that the variables exist before presenting them as you cannot guarantee their existence.
if(isset($_POST['email']) {
echo $_POST['email'];
}
This will check to see if $_POST['email'] exists. If it does, it will echo its value, if it doesn't then it will show nothing.
Change
<form action="welcome_get.php" method="get">
to
<form action="welcome_get.php" method="post">
as you are posting the values..Read more here
and again, you dont have a file named welcome_get.php (i understood from the error you got). It should be welcome.php. so replace ypur <form> tag as follows
<form action="welcome.php" method="post">

Base_url() is adding unnecessary segments into my url?

My base_url() is adding more bits into the url than it should be. What is wrong with my setup? I have the helper set up in config.php:
$autoload['helper'] = array('url');
My base_url() is set to: index.php/
So the problem is that when I activate this form:
<h1>sometimes haikus don't make sense refrigerator</h1>
<form action="<?php echo base_url(); ?>welcome/login_submit" method="post">
<label>
email:
<input id="email" name="email" />
</label>
<label>
password:
<input type="password" id="password" name="password" />
</label>
<input type="submit" value="Log me in!" />
</form>
The first time I access it, I'll type in: localhost/CIintranet/ and the the base_url() gets added next so it becomes: localhost/CIintranet/index.php/
I'm trying to program a login logout system though. So if the user login is incorrect, I want it to redirect back to the login page. Here's the code from the controller for that part:
public function login_submit() {
$this->load->model('LoginChecker', 'users');
//$this->load->view('login_submit');
$match = $this->users->authenticate_user( $_POST['email'], $_POST['password'] );
if( $match )
{
$this->load->view('login_submit');
echo "User exists in database!";
}
else
{
$this->load->view('login_form');
echo "<h1>Email or password is wrong, bretheren!</h1>";
}
}
But when it reloads the login_form, it adds another part into the url and the url fails. So the progression is like this:
Page loads to this url:
localhost/CIintranet/
First failed attempt (page still loads properly):
localhost/CIintranet/index.php/welcome/login_submit
Second failed attempt (page fails to load):
localhost/CIintranet/index.php/welcome/index.php/welcome/login_submit
I've been doing some research on this for a bit now and I'm noting a lot of people talking about the htaccess file in relation to this problem but nobody seems to mention specifically what fixes it or how to configure the base_url() so that it just takes care of this properly. I tried looking at the documentation but perhaps I missed something. I didn't find what I was looking for.
Any ideas?
Can you try setting the base_url to /index.php/? So it has the forward slash at the front too?
Failing that, please try: http://localhost/CIintranet/index.php/
It's usually the simple things!
if you use ... ?
<?php echo form_open('welcome/login_submit') ?>
...
<?php echo form_close(); ?>
activate helper: form

POST without redirect with PHP

I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/
The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.
<form method="POST" action="mlml/process.php">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="submit" value="" id="submit"name="submit" >
</form>
You will need AJAX to post the data to your server. The best solution is to implement the regular posting, so that will at least work. Then, you can hook into that using Javascript. That way, posting will work (with a refresh) when someone doesn't have Javascript.
If found a good article on posting forms with AJAX using JQuery .
In addition, you can choose to post the data to the same url. The JQuery library will add the HTTP_X_REQUESTED_WITH header, of which you can check the value in your server side script. That will allow you to post to the same url but return a different value (entire page, or just a specific response, depending on being an AJAX request or not).
So you can actually get the url from your form and won't need to code it in your Javascript too. That allows you to write a more maintanable script, and may even lead to a generic form handling method that you can reuse for all forms you want to post using Ajax.
Quite simple with jQuery:
<form id="mail_subscribe">
<input type="text" name="address" id="email" maxlength="30" size="23">
<input type="hidden" name="action" value="subscribe" />
<input type="submit" value="" id="submit"name="submit" >
</form>
<p style="display: none;" id="notification">Thank You!</p>
<script>
$('#mail_subscribe').submit(function() {
var post_data = $('#mail_subscribe').serialize();
$.post('mlml/process.php', post_data, function(data) {
$('#notification').show();
});
});
</script>
and in your process.php:
<?php
if(isset($_POST['action'])) {
switch($_POST['action']) {
case 'subscribe' :
$email_address = $_POST['address'];
//do some db stuff...
//if you echo out something, it will be available in the data-argument of the
//ajax-post-callback-function and can be displayed on the html-site
break;
}
}
?>
It redirects to a different page because of your action attribute.
Try:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<input type="text" name="address" id="email" maxlength="30" size="23" />
<input type="submit" value="" id="submit" name="submit" />
</form>
<?php if (isset($_POST['submit'])) : ?>
<p>Thank you for subscribing!</p>
<?php endif; ?>
The page will show your "Thank You" message after the user clicks your submit button.
Also, since I don't know the name of the page your code is on, I inserted a superglobal variable that will insert the the filename of the currently executing script, relative to the document root. So, this page will submit to itself.
You have to use AJAX. But that requires JavaScript to be active at the users Brwoser.
In my opinion it's the only way to do without redirect.
to send a form request without redirecting is impossible in php but there is a way you can work around it.
<form method="post" action="http://yoururl.com/recv.php" target="_self">
<input type="text" name="somedata" id="somedata" />
<input type="submit" name="submit" value="Submit!" />
</form>
then for the php page its sending to have it do something but DO NOT echo back a result, instead simply redirect using
header( 'Location: http://yourotherurl.com/formpage' );
if you want it to send back a success message simply do
$success = "true";
header( 'Location: http://yourotherurl.com/formpage?success='.$success);
and on the formpage add
$success = $_GET['success'];
if($success == "true"){ echo 'Your success message'; } else { echo
'Your failure message';
Return and print the contents of another page on the current page.
index.php
<html>
<body>
<p>index.php</p>
<form name="form1" method="post" action="">
Name: <input type="text" name="search">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$_POST['search'];
include 'test.php';
}
?>
</body>
</html>
test.php
<?php
echo 'test.php <br/>';
echo 'data posted is: ' . $_POST['search'];
?>
Result:
Just an idea that might work for you assuming you have no control over the page you are posting to:
Create your own "proxy php target" for action and then reply with the message you want. The data that was posted to your php file can then be forwarded with http_post_data (Perform POST request with pre-encoded data). You might need to parse it a bit.
ENGLISH Version
It seems that no one has solved this problem without javascript or ajax
You can also do the following.
Save a php file with the functions and then send them to the index of your page
Example
INDEX.PHP
<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
Tools.php (It can be any name, note that it is kept in a folder lame tools)
<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}
if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
Use
form onsubmit="takeActions();return false;"
function takeAction(){
var value1 = document.getElementById('name').innerHTML;
// make an AJAX call and send all the values to it
// Once , you are done with AJAX, time to say Thanks :)
document.getElementById('reqDiv').innerHTML = "Thank You for subscribing";
}

Calling a PHP function from an HTML form in the same file

I'm trying to execute a PHP function in the same page after the user enters a text and presses a submit button.
The first I think of is using forms. When the user submits a form, a PHP function will be executed in the same page. The user will not be directed to another page. The processing will be done and displayed in the same page (without reloading).
Here is what I reach to:
In the test.php file:
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
The PHP code [ test() function ] is in the same file also:
<?php
function test() {
echo $_POST["user"]; // Just an example of processing
}
?>
However, I still getting a problem! Does anyone have an idea?
This cannot be done in the fashion you are talking about. PHP is server-side while the form exists on the client-side. You will need to look into using JavaScript and/or Ajax if you don't want to refresh the page.
test.php
<form action="javascript:void(0);" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
$("form").submit(function(){
var str = $(this).serialize();
$.ajax('getResult.php', str, function(result){
alert(result); // The result variable will contain any text echoed by getResult.php
}
return(false);
});
</script>
It will call getResult.php and pass the serialized form to it so the PHP can read those values. Anything getResult.php echos will be returned to the JavaScript function in the result variable back on test.php and (in this case) shown in an alert box.
getResult.php
<?php
echo "The name you typed is: " . $_REQUEST['user'];
?>
NOTE
This example uses jQuery, a third-party JavaScript wrapper. I suggest you first develop a better understanding of how these web technologies work together before complicating things for yourself further.
You have a big misunderstanding of how the web works.
Basically, things happen this way:
User (well, the browser) requests test.php from your server
On the server, test.php runs, everything inside is executed, and a resulting HTML page (which includes your form) will be sent back to browser
The browser displays the form, the user can interact with it.
The user submits the form (to the URL defined in action, which is the same file in this case), so everything starts from the beginning (except the data in the form will also be sent). New request to the server, PHP runs, etc. That means the page will be refreshed.
You were trying to invoke test() from your onclick attribute. This technique is used to run a client-side script, which is in most cases Javascript (code will run on the user's browser). That has nothing to do with PHP, which is server-side, resides on your server and will only run if a request comes in. Please read Client-side Versus Server-side Coding for example.
If you want to do something without causing a page refresh, you have to use Javascript to send a request in the background to the server, let PHP do what it needs to do, and receive an answer from it. This technique is basically called AJAX, and you can find lots of great resources on it using Google (like Mozilla's amazing tutorial).
Here is a full php script to do what you're describing, though pointless. You need to read up on server-side vs. client-side. PHP can't run on the client-side, you have to use javascript to interact with the server, or put up with a page refresh. If you can't understand that, there is no way you'll be able to use my code (or anyone else's) to your benefit.
The following code performs AJAX call without jQuery, and calls the same script to stream XML to the AJAX. It then inserts your username and a <br/> in a div below the user box.
Please go back to learning the basics before trying to pursue something as advanced as AJAX. You'll only be confusing yourself in the end and potentially wasting other people's money.
<?php
function test() {
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" standalone=\"yes\"?><user>".$_GET["user"]."</user>"; //output an xml document.
}
if(isset($_GET["user"])){
test();
} else {
?><html>
<head>
<title>Test</title>
<script type="text/javascript">
function do_ajax() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var xmlDoc = xmlhttp.responseXML;
data=xmlDoc.getElementsByTagName("user")[0].childNodes[0].nodeValue;
mydiv = document.getElementById("Test");
mydiv.appendChild(document.createTextNode(data));
mydiv.appendChild(document.createElement("br"));
}
}
xmlhttp.open("GET","<?php echo $_SERVER["PHP_SELF"]; ?>?user="+document.getElementById('username').value,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" id="username"/>
<input type="button" value="submit" onclick="do_ajax()" />
</form>
<div id="Test"></div>
</body>
</html><?php } ?>
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
Use SAJAX or switch to JavaScript
Sajax is an open source tool to make
programming websites using the Ajax
framework — also known as
XMLHTTPRequest or remote scripting —
as easy as possible. Sajax makes it
easy to call PHP, Perl or Python
functions from your webpages via
JavaScript without performing a
browser refresh.
That's now how PHP works. test() will execute when the page is loaded, not when the submit button is clicked.
To do this sort of thing, you have to have the onclick attribute do an AJAX call to a PHP file.
in case you don't want to use Ajax , and want your page to reload .
<?php
if(isset($_POST['user']) {
echo $_POST["user"]; //just an example of processing
}
?>
Take a look at this example:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>
E-mail: <input type="text" name="email">
<br><br>
Website: <input type="text" name="website">
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
You can submit the form without refreshing the page, but to my knowledge it is impossible without using a JavaScript/Ajax call to a PHP script on your server. The following example uses the jQuery JavaScript library.
HTML
<form method = 'post' action = '' id = 'theForm'>
...
</form>
JavaScript
$(function() {
$("#theForm").submit(function() {
var data = "a=5&b=6&c=7";
$.ajax({
url: "path/to/php/file.php",
data: data,
success: function(html) {
.. anything you want to do upon success here ..
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
Upon submission, the anonymous Javascript function will be called, which simply sends a request to your PHP file (which will need to be in a separate file, btw). The data above needs to be a URL-encoded query string that you want to send to the PHP file (basically all of the current values of the form fields). These will appear to your server-side PHP script in the $_GET super global. An example is below.
var data = "a=5&b=6&c=7";
If that is your data string, then the PHP script will see this as:
echo($_GET['a']); // 5
echo($_GET['b']); // 6
echo($_GET['c']); // 7
You, however, will need to construct the data from the form fields as they exist for your form, such as:
var data = "user=" + $("#user").val();
(You will need to tag each form field with an 'id', the above id is 'user'.)
After the PHP script runs, the success function is called, and any and all output produced by the PHP script will be stored in the variable html.
...
success: function(html) {
alert(html);
}
...
This is the better way that I use to create submit without loading in a form.
You can use some CSS to stylise the iframe the way you want.
A php result will be loaded into the iframe.
<form method="post" action="test.php" target="view">
<input type="text" name="anyname" palceholder="Enter your name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<iframe name="view" frameborder="0" style="width:100%">
</iframe>

Categories