How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}
I have a facebook app in php that working without any problem of authentication. so users log in and the app gets required permissions and they navigate through the pages. but
I have a page called sender.php that need to repeat 8 times.
So here is the scenario that is not working:
1)users are in sender.php
2)they click submit,(as action form is set to "sender.php") the browser again shows sender.php form
3) a user again enter something in text input, and click on submit button
4) a blank page shows without anything;
(note thatit is only works for the first click, for second time it only shows a blank page without any errors or notice.)
here is html code in sender.php:(the first php codes using here are the same for the rest of php pages and working without any error)
<?php
require_once("config.php");
require_once("database.php");
require_once("facebook_include1.php");
ini_set('display_errors', 1);
error_reporting(E_ALL);
$me = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
$user = $facebook->getUser();
if (isset($_GET['moneySent'])) {
$moneySent = round($_GET['moneySent']);
$senderBalance = $_GET['balance'];
$senderRate = $_GET['senderRate'];
$receiverRate = $_GET['receiverRate'];
}
?>
<script type="text/javascript">
function validateForm() {
var isValid = true;
var moneySent = document.getElementById("moneySent").value;
var balance = document.getElementById("balance").value;
if (!document.getElementById("moneySent").value.length)
{
delete window.alert;
alert("Please enter an amount you want to send!.");
isValid = false;
}
else if (isNaN(moneySent))
{
delete window.alert;
alert("Please enter a numeric value.");
isValid = false;
}
else if (Math.round(moneySent) > balance) {
delete window.alert;
alert("The amount you want to send should be less than your balance.");
isValid = false;
}
return isValid;
}
</script>
<form action="sender.php" method="get" name="sendFor" onsubmit="return validateForm();">
<div class="yui-u">
<input type="text" id="moneySent" name="moneySent" style="width:100px"/>
<input type="hidden" name="balance" id="balance" value='<?php echo $senderBalance ?>'/>
<input type="hidden" name="senderRate" id="senderRate" value='<?php echo $senderRate ?>'/>
<input type="hidden" name="receiverRate" id="receiverRate" value='<?php echo $receiverRate ?>'/>
</div>
<div class="yui-u">
<input type="submit" name="btnsearch" id="btnsearch" value=" Send > " class="search" style="margin-left:-6.5px" /><br />
</div>
</form>
any thought is really appreciated. I am using php5 and apache with the latest facebook sdk for php.
UPDATED:
I've tested in Firefox. However, if I use IE8 and add target="_blank" to the form tag, the page is going out of facebook canvas but start working normally, any idea?
I have changed action="sender.php" to action="#" and it is working in both IE and firefox.
Not sure what is the difference though!!
I have a contact form that I'm using Jquery .load to import a php file into any of the pages the nav will be on. Example below.
http://madaxedesign.co.uk/dev/index.html
I'm aware that the action form needs to be changed so it is connected to the right place. But how would I do that if it is on different pages and imported into a page. Because at the moment it is set to contact.php but after it is submitted it goes to that page and doesn't import the message into the pop up. So really I need it to be the file name depending on what page it is on.
So I suppose the question is how do I get the message after submit to appear inside the pop up instead of on a different page?
Code:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form method="post" action="contact.php">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div>
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
$referer = $_SERVER['HTTP_REFERER'];
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt ;p.";
exit;
}
mail($your_email, $subject, $message, "From: $name <$email>");
echo $thankyou_message;
}
?>
You should use ajax, send the email without refreshing page.
What you want to do is only possible in javascript, this is a language that gets executed by the browser. Javascript self is a nasty language but there are many extensions/plugins to make this very easy like jQuery. i suggest you to learn this language, you will find a new world opening in web development ;-). eg: http://learn.jquery.com/
give your form an id:
<form method="post" id="test-form" action="contact.php">
so you can reference to it with jquery
now you can catch the form submit action with jQuery:
$('#test-form').submit(function() {
//send your data to your server and get the html data
$.post('contact.php', $(this).serialize(), function (data){
//here you can add the (html)data returned by the action to your page.
$('body').append(data); //append data to body of html page
})
return false; //stop form from going to the next page
});
this code is based on a javascript plugin: jQuery, if you want to do anything dynamic on your page without reloading the page, you need to use javascript.
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>
I do know how to validate a basic input(text) when submitting a form. However, I am lost as to how I am going to validate an input(text) when leaving a web page. Even with JS I couldn't get it to stay on the same page due to the "form action" attribute.
HTML Code for the input and submit
<form name="form1" action="second.php" **onsubmit="return error()"** method="post">
<input style="" name="hall" type="text"><br>
<input name="Move" style="height: 23px" type="submit" value="Move">
</form>
PHP CODE for validating
<?php
if (isset($_POST['Move'])) {
if(($_POST['hall']) != "Hallway")
{
echo "Not among available rooms";
}
?>
Also this is the JS code
<script type="text/javascript">
function error()
{
var x=document.forms["form1"]["hall"].value
if (x==null || x=="" || x!="next")
{
alert("Wrong entry. Try again!!!");
return false;
}
}
</script>
The following code is working on my server, provided the second.php page exists. (BTW I added a ; after value, but it seems to work without it).
Did you put the js script after the form? Maybe it could impact.
<html>
<script type="text/javascript">
function error()
{
var x=document.forms["form1"]["hall"].value;
if (x==null || x=="" || x!="next")
{
alert("Wrong entry. Try again!!!");
return false;
}
}
</script>
<body>
<form name="form1" action="second.php" onsubmit="return error()" method="post">
<input style="" name="hall" type="text"><br>
<input name="Move" style="height: 23px" type="submit" value="Move">
</form>
</body>
</html>
Other things I can think of:
-Do you have any JS errors on the page that would prevent this script from running? It worked on my server, as well.
-Do you have another HTML element with an identical name?
-I am assuming that the **'s were for emphasizing that area in your code. If not, of course, they would need to be removed.
The only thing that could prevent your "return false" from working is if you have some kind of JavaScript error that kills the script from running.
If you have additional code on your page, please post it and we'll take a look!