Using forms from a tabbed index page - php

So I'm new to PHP and I'm having trouble getting some of my forms to function. I think it may be the way my site is set up that's causing me problems.
I have index.php which is set up as such:
<div class="pageContent">
<div id="main" style="width:1000px; margin:0 auto;">
<!-- Create the tabs -->
<div id="tabs" >
<ul>
<li>Overview</li>
<li>Ranked</li>
<li>Arena</li>
<li>Decks</li>
<li>New Game</li>
<li>Admin</li>
</ul>
<div id="tabs-0"></div>
<div id="tabs-1"></div>
<div id="tabs-2"></div>
<div id="tabs-3"></div>
<div id="tabs-4"></div>
<div id="tabs-5"></div>
</div>
<!-- Load the pages into tabs -->
<script>
$("#tabs").tabs();
$("#tabs-0").load("tab0.php");
$("#tabs-1").load("tab1.php");
$("#tabs-2").load("tab2.php");
$("#tabs-3").load("tab3.php");
$("#tabs-4").load("newGame.php");
$("#tabs-5").load("admin.php");
</script>
</div><!-- / main -->
</div><!-- / pageContent -->
This gives me a nice static page and 6 tabs of .php files to do cool stuff on.
There are a couple of forms, log in and such, in index.php which all function fine. But when I create a form on a page in a tab, it will not.
Here's an example from admin.php (#tabs-5)
<?php
if(isset($_POST['delLog'])){
unlink('log.txt');
echo 'Success';
}
if(isset($_POST['delLog'])){
unlink('error_log');
echo 'Success';
}
?>
<html>
<head>
</head>
<body>
<table width="100%" border="1">
<tr>
<td width="40%" valign="top">
</td>
<td width="30%" valign="top">
<h1>error_log</h1>
<form action="" method="post">
<input type="submit" name="delErr" id="delErr" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('error_log'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
<td width="3'0%" valign="top">
<h1>log.txt</h1>
<form action="" method="post">
<input type="submit" name="delLog" id="delLog" value="Delete" />
</form>
<hr />
<?php
$lines = explode("\n", file_get_contents('log.txt'));
foreach ($lines as $line){
echo $line.'<br>';
}
?>
</td>
</tr>
</table>
</body>
</html>
This is another, better example. A stripped down test I did yesterday for this question
Problems with $_POST
<?php
define('INCLUDE_CHECK',true);
include 'php/functions.php';
error_reporting(E_ALL);
ini_set('display_errors',1);
logThis('ready!');
if (isset($_POST['submit'])) {
logThis('success');
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>
</html>
Neither of these examples work. When the submit button is pressed the site refreshes but no PHP actions are taking place. There is no error message in error_log. I don't think it's getting the call at all.
Neither of the forms return an output, one adds to the database. The other deletes log files.
Hope I've provided enough details.

What ever you are trying to do is not possible at all. You can not load PHP code to frontend, it can only be processed by the server.
The statement $("#tabs-5").load("admin.php"); is fetching only the html code (processed by the server) not the PHP script

<form action="" method="post"> will post to the current page (ie. whatever is in your address bar).
When you load the pages into index.php using ajax, that means the forms will post to index.php... I'm guessing you are expecting to fetch the form submissions in each individual php-file
So to fix it either you have to also post using ajax (and refresh the tabs with the response), or you need to change the action attribute on the forms to each individual php-file... in which case you lose your tabbed layout when a form is submitted. You can work around that as follows:
In each of the php-files you do something like this (using newGame.php as example):
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
// ...and then redirect back to index.php
header("Location: index.php");
die();
} else {
//Print your form
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
}
Note that there should be no <html>, <head>, <body> or other html in the "sub-pages" at all - just the bare content you want inside the tabs...
Now for the ajax-submit method you should also remove all "wrapping html", you should still set a target="[...]" on each form, and you should still do form handling inside each individual file. But you should not do a redirect after form handling, but just output the form again:
<?php
if (isset($_POST)) {
//Do your form-handling stuff first
// [...]
//Maybe print a little message to let the user know something happened
echo 'Form completed at ' . date('H:i:s');
}
//...then print your form no matter what
echo '<form action="newGame.php" method="post">';
// [...]
echo '<input type="submit" value="Create game">';
echo '</form>';
Then add this script to index.php - it will post all forms inside the tabs using ajax instead of refreshing the page:
<script>
my_cool_ajax_post = function(form_elm, tab_elm) {
//Actual ajax post
$.post(form_elm.target, $(form_elm).serialize(), function(data){
//Results are in, replace tab content
tab_elm.html(data);
});
};
$(document).on("submit", "#tabs form", function(){
//Store the form element
var form_elm = this;
//Find the parent tab element
var tab_elm = $(this).closest('#tabs > div');
//Really simple "loader"
tab_elm.html('<p>loading...</p>');
//Submit by ajax
my_cool_ajax_post(form_elm, tab_elm);
return false;
});
</script>
Disclaimer: Completely untested, so let me know...

Related

Re-populate fields after form submission and redirection PHP ONLY

I am supposed to have my form elements repopulate using php and html only after I click the link from page two. However, none of the fields are repopulating. Please help me!!?
Page 1:
<?php
session_start();
?>
<?php
/*
This page should:
1) Use a cookie (NOT PHP SESSION) that expires a year from now to do the following:
Record the timestamp of the FIRST load of this page (but NOT any subsequent load of this page).
Note: You only need first 3 parameters in setcookie() for this HW.
2) If the suvey was already completed, transfer to third page (thank you page).
That page instructs you to set a cookie that will allow you to detect this.
Recall from the CRUD example how page transfers are done in PHP:
header("Location: URL");
3) The form in this page should submit to THIS PAGE, and then transfer to hw_page2.php
after saving stuff to PHPs built-in $_SESSION superglobal.
The data will then be available in all the other pages (remember no database is allowed for this HW).
4) If the button in the 2nd page is clicked to come back to this page, the
Session data should re-populate into the form.
*/
if (!isset($_COOKIE['load_date'])) {
setcookie('load_date', time(), time() + (86400 * 365));
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Profile</title>
</head>
<body>
<h3><?=$message?></h3>
User Profile:
<?php
$load_date = $_COOKIE['load_date'];
$_SESSION['is_cool'] = $_POST['is_cool'];
$_SESSION['like_bands'] = $_POST['like_bands'];
$_SESSION['other_band'] = $_POST['other_band'];
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
print_r($bands);
echo $other_band;
echo $is_cool;
?>
<br><br>
<form action="hw_page1.php" method="POST" name="form1" onsubmit="return validate_form()">
<input type="hidden" name="task" value="process_profile">
<input type="checkbox" name="is_cool" value= "yes" <?php if ($is_cool == 'yes') {
echo 'checked = "yes"';
}?>>
Are you cool?
<br><br>
What Bands do you like?
<br>
<select name="like_bands[]" multiple> <small>* Required Field</small>
<option value="Sabbath" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?>> Black Sabbath</option>
<option value="Mastodon" <?php if (isset($_SESSION['like_bands']) && in_array("Mastodon", $bands)) {
echo 'selected';
} ?> >Mastodon</option>
<option value="Metallica" <?php if (isset($_SESSION['like_bands']) && in_array("Metallica", $bands)) {
echo 'selected';
} ?> >Metallica</option>
<option value="Swift" <?php if (isset($_SESSION['like_bands']) && in_array("Swift", $bands)) {
echo 'selected';
} ?> >Taylor Swift</option>
</select>
<br><br>
Favorite band not in the above list.
<br>
<input type="text" name="other_band" value="<?=$other_band?>">
<br><br>
<button type="submit" name= 'submit' value = 'submit'> Continue/Confirm </button>
</form>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Client-side form validation
// Don't change the names of stuff in the form, and you won't have to change anything below
// Used built-in JS instead of JQuery or other validation tool
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function validate_form() {
var form_obj = document.form1;
var count_liked = 0;
for (var i=0 ; i < form_obj['like_bands[]'].options.length ; i++ ) {
if (form_obj['like_bands[]'].options[i].selected) {
count_liked++;
}
}
if (count_liked == 0) {
alert("You must choose a band from the menu.");
return false; // cancel form submission
}
return true; // trigger form submission
}
</script>
<?php
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
echo $_SESSION['is_cool'];
if (isset($_SESSION['like_bands'])) {
header('Location: hw_page2.php');
}
?>
</body>
</html>
My second Page:
<?php
session_start();
/*
This page should:
1) Transfer back to hw_page1.php if loaded directly without the survey being completed (no survey data in session).
2) Display the Survey Data submitted from the previous page.
3) The form in this page should submit to THIS PAGE.
Use PHP to validate that the form below is completed.
Validate that the signature is not the empty string or only blank spaces (use PHP trim() function)
And of course validate that the checkbox was checked.
If the validation passes, save the signature into SESSION ande transfer to hw_page3.php.
If the validation fails, don't transfer.
Instead, back through to the form in this page WITH an appropriate message.
In that case, the Survey Data MUST also re-display in this page.
Note:
hw_page1.php used client-side JavaScript validation to ensure that all data was collected.
For the form below. do NOT use client-side JavaScript validation, but rather use PHP as instructed above.
Client-side validation is convenient for the end user, but can be bypassed by someone with know-how.
*/
?>
<?php
if (!isset($_SESSION['is_cool']) and !isset($_SESSION['like_bands'])) {
header('Location: hw_page1.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Verify Profile</title>
</head>
<body>
<?php
$is_cool = $_SESSION['is_cool'];
$bands = $_SESSION['like_bands'];
$other_band = $_SESSION['other_band'];
echo $is_cool;
print_r($bands);
echo $other_band;
$_SESSION['is_cool'] = $is_cool;
$_SESSION['like_bands'] = $bands;
$_SESSION['other_band'] = $other_band;
$bandslist = "";
foreach ($bands as $band) {
$bandslist .= "$band, ";
}
?>
<!-- Display Survey Data Here -->
<table width="" border="1" cellspacing="0" cellpadding="5">
<tr valign="top">
<td>Are you cool?</td>
<td>Liked Bands</td>
<td>Other Favorite Band</td>
</tr>
<tr valign="top">
<td><?= $_SESSION['is_cool']; ?></td>
<td><?= $bandslist; ?></td>
<td><?= $other_band; ?></td>
</tr>
</table>
<br><br>
<form action="hw_page2.php" method="GET" >
Verify that your profile data shown above is accurate by signing below.
<br>
<input type="text" name="signature" value="" placeholder="Sign Here">
<br>
<input type="checkbox" name="user_certify" value="yes">
I certify, under penalty of purgery, that my profile is accurate.
<br><br>
<button type="button" onclick="window.location='hw_page1.php';"> Go Back: Edit Profile Before Signing </button>
<!-- This is NOT a Submit Button! -->
<br>
<button type="submit"> Record Profile </button>
<!-- This is obviously -->
</form>
</body>
</html>
Please help me figure out where I am making a mistake! I have been working on it for days but I cannot figure out the answer.

How to prevent form submission on page load/refresh in php?

I am working on a html/php code as shown below in which I want to call a particular section of php code on click of a button.
<html>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['go-button'])) {
for each ($mp4_files as $f) {
}
}
?>
<form action ="" method="POST">
<table>
<td style="width:5%; text-align:center;"><button style="width:90px;" type="submit" name="go-button" value="Go" class="btn btn-outline-primary">Go</button> <!-- Line#B -->
</table
</form>
</html>
On click of a button at Line#B, the php code is call above and it goes inside the if block.
The issue which I am having right now is that on refresh of a page, it is also going inside the if block which I don't want to happen. I want if block to be active only on click of Go button.
Problem Statement:
I am wondering what changes I should make in the php code above so that on refresh of a page it doesn't go inside the if block. It should go only on click of a button at Line#B.
I'm not sure where you were having issues as such - in one comment you virtually hit the nail on the head as it were with how to prevent the form being re-submitted if the user reloads the page. You ought to be able to adopt an approach like the following - though if the PHP does generate content and it located within the document body somewhere you'd need to use output buffering to prevent errors regarding headers already sent
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' and !empty( $_POST['go-button'] ) ) {
foreach( $mp4_files as $f ) {
/* do stuff */
}
/* finished processing POST request, redirect to prevent auto re-submission*/
exit( header( sprintf('Location: %s', $_SERVER['SCRIPT_NAME'] ) ) );
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST">
<table>
<tr>
<td style="width:5%; text-align:center;">
<!-- Line#B -->
<button style="width:90px;" type="submit" name="go-button" value="Go" class="btn btn-outline-primary">Go</button>
</td>
</tr>
</table>
</form>
</body>
</html>

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

php session displaying previous session values

I am calling a console application from php which gives me some output. I have to display the output in a div after the console application is executed. I have passed the output from the console application as a SESSION to another page to display it. I have used ajax and javascript in my webpage too which make it more complicated. Now when I print the output the output in the div is the previous value of the SESSION.My code is as follows:
The main page:
<!DOCTYPE html>
<html>
<head>
$('#file').live('change', function()
{
$("#preview").html('');
$("#preview").html('<img src="images/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
<script type="text/javascript">
function myfunction()
{
$("#display").html('');
$("#display").html('<img src="images/loader.gif" alt="Uploading...."/>');
$("#retrieveimageform").ajaxForm(
{
target: '#display'
}).submit();
$('#tags').html('<?php include 'Tagsdisplay.php';?>');
%I want to include this only after it goes through the retrieveimage1.php page
where the console application is called and the session is created but this is
not happening the tags div is shown before the console application is called
and the other results are displayed on the display div
$('#tags').show();
};
</script>
<title></title>
</head>
<body>
<div id="maindiv">
<div id="banner">
<?php
include 'Header.php';
?>
</div>
<div id="wrapper">
<div id="imageupload">
<form action="uploadimage.php" method="post"
enctype="multipart/form-data" id="imageform">
<label for="file">Upload your image:</label>
<input type="file" name="file" id="file"><br>
</form>
</div>
<div id='preview'>
</div>
<div id='tags'>
</div>
<div class="clear"></div>
<form action="retrieveimage1.php" method="post"
id="retrieveimageform">
................................
<input type="submit" name="search" value="Search" id="btnSearch" onclick="myfunction()">
</form>
<div id="display"></div>
</div>
The retrieveimage.php where the console app is called and session is created:
session_start();
$start_time= microtime(true);
if (isset($_SESSION['img']))
{
$image=$_SESSION['img'];
$_SESSION['coarselbl1']=" ";
$_SESSION['coarselbl2']=" ";
$_SESSION['coarselbl3']=" ";
$_SESSION['finelbl1']=" ";
$_SESSION['finelbl2']=" ";
$_SESSION['finelbl3']=" ";
$_SESSION['finelbl4']=" ";
$_SESSION['category']=" ";
if($_POST['cat']=='handbag')
{
$_SESSION['category']="Bag";
$cwt=$_POST["slider1"];
$fwt=$_POST["slider2"];
$twt=$_POST["slider3"];
$swt=$_POST["slider4"];
$addr="handbags31_fourth.exe $image $cwt $fwt $swt $twt";
exec($addr,$data);
$_SESSION['coarselbl1']=$data[2];
$_SESSION['coarselbl2']=$data[3];
$_SESSION['coarselbl3']=$data[4];
}
The TagsDisplay.php where the tags are displayed:
<?php
session_start();
echo $_SESSION['category']."<br/>";
if($_SESSION['category']=="Bag")
{
echo "Coarse Color: ".$_SESSION['coarselbl1'].",".$_SESSION['coarselbl2'].",".$_SESSION['coarselbl3']."<br/>";
unset($_SESSION['coarselbl1']);
unset($_SESSION['coarselbl2']);
unset($_SESSION['coarselbl3']);
}
?>
The problem here is when I click the search button the myfunction is called and the tags div is displayed before the display div and the value printed are the previous session value. I want the tag div to come only after the display div is shown and the new session are assigned. How can I achieve that?
Fix the jquery line
$('#tags').html('<?php include 'Tagsdisplay.php';?>');
to this:
$('#tags').html('<?php include "Tagsdisplay.php";?>');
(note the quotes) because you are not even including the file that unsets the previous session's values.

PHP Pass variable to popup form within same page

Following on from a previous question, (previous question here), the problem I'm having seems to involve trying to pass/post a value through a form when the form action is '#'. I've tried session data but it always returns the last item from the database. Everthing else returns nothing.
Any help/ideas/advice greatly received, S. (Code below)
This is the code that displays the list of items, each containing an 'email' link/button to one instance of a popup window/form that is located at the bottom of the page.
<?php
$query = mysql_query("select * from istable where categoryID = '1'");
while ($result = mysql_fetch_array($query)) {
echo '<h4>'.$result['title'].'</h4>
<p>'.substr($result['descrip'],0,408).'... <strong>Read more</strong></p>
<form action="#" method="post" rel="#sheet" class="see">
<input type="hidden" name="propTitle" value="'.$propResult['title'].'">
<input type="submit" name="submit" value="Email">
</form>
';
}
?>
This is the code for the popup window/form at the bottom of the same page that is called through jquery.
<div id="sheet" class="rounded">
<!--{{{ pane1 -->
<div class="pane" id="pane1">
<h4>Email Details to a Friend</h4>
<p>You have selected to forward the details of <?php echo $_POST['propTitle']; ?> to a friend.</p>
<p>Please fill out the following form</p>
<form class="rounded" id="email-form" method="post" action="<?php echo $pageLink; ?>">
<!-- form goes in here -->
</form>
</div>
<!--}}}-->
</div>
<script type="text/javascript">
$(".see").overlay({mask: '#999', fixed: false}).bind("onBeforeClose", function(e) {
$(".error").hide();
});
</script>
Why are you using PHP for this? If the popup is called through the same page, use JavaScript to get the DOM element value and if you need to process data use AJAX.

Categories