form session data not posting, sessions working - php

I've been tinkering with this for a few days. Checked out all the posts related and still can't quite get it to work. Anyone able to take a look and steer me in the right direction?
I have a site where everything gets loaded into a div on a page.
everything is working great except the form data.
I can load the session data for a test and it works fine, however i can't seem to get any of the entered form data.
i have the session_start(); included at the top just under the opening php tag in connection.php. connection.php is required on each page.
connection.php beginning.
<?
session_start();
Here are some code samples from addvehicle.php (not posting it all as it's huge and the rest is not relevant, can if need be though)
...
<script type="text/javascript">
$(document).ready(function()
{
$('form#newvehicleform').submit(function()
{
<?php
$trucknumbera=$_POST["trucknumber"];
$_SESSION['trucknumber']=$trucknumbera;
$_SESSION['info']="this is some info";
?>
$("#mainwindow").load("addvehiclepost.php");
return false;
});
});
</script>
.....
<form id="newvehicleform" class="newvehicleform" method="post" action="<?php echo $PHP_SELF;?>">
<table>
<tr>
<td>
Truck Number
</td>
<td>
<input name="trucknumber" class="validate[required,custom[number]]" type="text" id="trucknumber" autofocus autocomplete="off" required />
</td>
</tr>
<tr>
<td>
<br>
<input type="submit" id="submit" class="s-submit" alt="Submit" value="Submit">
</td>
</tr>
</table>
</form>
the test of, addvehiclepost.php
require ('./connection.php');
echo "<br>info: " .$_SESSION['info']. "<br>";
$trucknumber=$_SESSION['trucknumber'];
echo "<br>trucknumber: " .$trucknumber;
and here is the output i get from addvehiclepost.php
info: this is some info
trucknummer:
so you can see it's passing the $_SESSION properly and that function is working however I just can't get it to pass the submitted for data.
Anyone have any ideas on getting this to go?
Thanks in advance.
-Colin.

When you execute your first script with PHP, there is no form data.
And the PHP fragment executed there does not do anything besides transfering an empty POST value (NULL) to a local variable and then to the session array.
I think you think that this PHP code gets executed when the javascript is called, but this is not the case! First all PHP is executed, and the result is echoed back to the browser. Then the page is rendered and javascript is executed.
So the PHP part of your code does copy an empty value (and sets a static one as well, that's what you see) at the time the form page is first loaded by the browser.
Then javascript acts. Which would mean in your case that there is no form POST request, but simply a GET request for the addvehiclepost.php script. No POST request means no $_POST data. Which isn't accessed in the loaded script anyway.
I don't know if you are able to fix this, but I hope I enabled you to understand the structural error of your code. I have seen this with about any newbie I know.

Related

PHP submit blank screen - script not running on POST?

I have a script that pulls an XML page and uses a form to update and save the values back. When I click the submit button it works, but then the page loads blank. I just want the page to refresh. There are about 100 different threads on this, and nothing I have tried has worked to resolve the issue. Out of curiosity, I just tried to run the window.location script and nothing else, and this piece actually doesn't work at all.
<?php
//if (isset($_POST['submit'])) {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//$ctstatus->nodeValue = $_POST['ctstatusform'];
//htmlentities($xml->save('test.xml'));
echo '<script type="text/javascript">window.location="http://google.ca";</script>';
}
?>
The inner contents of the form don't really matter at this point, I just want it to refresh the page after I hit the submit button.
I previously used isset but from reading it seems like that's obsolete, and my form action="" used to be blank. Either way my XML save works, but nothing to refresh the page. I also tried header and that didn't work either.
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class="save" name="submit" type="submit" value="Save" />
</form>
Out of curiosity I tried an onClick function with a timer and this does work but it's not ideal at all, especially because the page could technically refresh before the POST is finished writing the file. I'd rather know why the echo doesn't execute.
PHP redirect would most likely be preferable to JavaScript redirect.
Typical structure when posting back to same page:
<?php // cannot be any output before this (space, linefeed, etc)
if(isset($_POST['submit']) {
// do stuff with the submission
header('Location: http://google.ca');
exit;
}
// does your script need to do some other data retrieval or calculation? do it here.
?>
<html>
... snip ...
<form method="post">
... snip ...
<input class="save" name="submit" type="submit" value="Save" />
</form>
Following this simple structure for procedural scripts--
Deal with user input / redirect
Do logic (collect, manipulate data)
Show output (using php only to insert variables and looping)
will help you avoid a lot of heartache and technical debt.
Okay, I have gotten this sorted out. It turns out that the problem was embarrassingly simple, but maybe will assist someone in the future. Along with reordering my code, as Tim suggested. I specified HTML as the DOCTYPE, and that worked to resolve the issue. I no longer need to worry about refreshing the page after submit, because it refreshes as it should automatically. Thank you to everyone who commented.

(PHP) I can't get a form action PHP code to work

I am not sure what i am doing wrong, but i cannot get a PHP form action page to work, when i attempt to run it, it takes me to a blank page that does nothing. I am trying to create a simple code that redirects the user to a page depending on the input on the form. Here is what my form code looks like:
<form action="index.php" method="post">
<font face="Stymie">ENTER SECRET CODE: <input type="text" name="secretcode"></font>
</form>
and here is what the index.php currently looks like:
<html>
<body>
<?php
if ($_POST['secretcode'] === "banana") {
header("Location: banana.php");
}
?>
</body>
</html>
This is one out of many codes i attempted to use, yet no matter what i put, it always takes me to a blank page. I also tried using GET instead of POST, but that just leaves me on the page without the code running.
Can someone tell me what i am suppose to do to get the code working? Help would be much appreciated.
UPDATE: I found a Javascript equivalent to this script which is a lot more efficient and simpler, thus i no longer need an answer.
<form onSubmit="return checkAnswer();">
<script>
function checkAnswer(){
var response = document.getElementById('secretcode').value;
if (response == "banana")
location = 'banana.html';
else
location = 'wrong.html';
return false;
}
</script>
Add a submit button:
<form action="index.php" method="post">
<font face="Stymie">ENTER SECRET CODE: <input type="text" name="secretcode"></font>
<button type="submit" name="submit" value="Enter"/>
</form>
And for the php code:
<?php
if (isset($_POST['submit'])) {
if($_POST['secretcode'] === "banana"){
header("Location: banana.php");
}
}
?>
I added the isset() to prevent possible Undefined index: errors when you expand the php codes
UPDATE
I just tried OP's codes, it is submitting even without a submit button (didn't know that, or maybe I just forgot).
It seems working for me, I am being redirected to banana.php when I typed banana in the input, the only problem I saw is the Undefined index error (which the isset() will solve it)

HTML and PHP in one file

I'm a PHP newbie trying to sort some basics out. I have a user-form that leads to a mysql select query, which works fine. Every tutorial I have found so far has the standard form tag, ie: action='script.php' method='post'. This obviously opens script.php in a new tab/window though.
If I don't want to display what's fetched from my db on a different webpage I have to put the html and php in one document together. I didn't think this is how you would really want to do it though.
My specific question is when you want to display stuff on the same page do you just put everything in together within one document and let users hit the submit button?
NO you dont put your php scripts on the same page as your html file/s
Try this link for your reference =)
OR you can put 2 different pages that act as 1 by using INCLUDE FUNCTION
script1.php
<form action="script2.php" method="post" name="myform">
...
<input type="submit" name='submit_button' value="Submit" />
<input
</form>
---------------
script2.php
include 'script1.php';
if(isset($_POST['submit_button']
{.......}
Yeah You can put html and php in single document.
With the help of action.But it not the proper way.
In action you should mention this for writing html and php in same page.
<?php echo htmlspecialchars ($_SERVER["PHP_SELF"]);?>
You can use the same page as Action in form and make condition based on your submit button whthere it is pressed or not.
If it is pressed you can make your Code there for connecting db and do operation like select, insert, update or delete.
e.g.
Your file: script.php
<?php
if(isset($_POST['btnsubmit'])) {
// Do your Operation here...
}
?>
<form action="script.php" method="post" name="myform">
...
<input type="submit" name="btnsubmit" value="Submit" />
<input
</form>
What you can do is simply refer the user back to the form, or another page on your server with the header tag. Inside your PHP script you'd add something similar after your query executes correctly
header( 'Location: ' . $_SERVER['HTTP_REFERER'] ); // Refer to the last page user was on...
Or another URI
header( 'Location: http://some.url/' );
If you really want to do this, here is a way:
<?php
if(isset($_POST)){
//do your php work here
}
?>
<html>
<form method='POST'>
//form elements here
<input type='submit'>
</form>
<!-- other html code -->
</html>
It depends on the length of your code, if the code is too much, then the better way is to include some script file to your parent file. using include() functions, and your perfect answer is yes. just put everything in together within one document

PHP script not executing

I have a form with 1222 fields (I know the number is large, but it's a form for saving translations). When I submit the form, the script is not executing. I get no error message and the error log is empty. Even if the script I post to contains only an echo command, nothing is executed and all I see is a blank page.
I am quite sure this is a PHP setting problem, as the form can be submitted without any problems on other servers. Can anyone shed some light on what the issue could be?
The HTML is:
<form action="test.php" method="post">
<input type="text" name="account-form-282f96c7d1ed98d24606d209dcad9842" value=""/>
<!-- 1221 more inputs with different names, but format is the same as above -->
<input type="submit" name="submitBT" value="Save"/>
</form>
test.php:
<?php
echo(1);
?>
Edit 1:
If I simplify the input names, e.g.: input_1, input_2 etc. the submit works fine.
Edit 2:
I noticed I receive a 406 Not Acceptable HTTP response.
The problem is with mod_security, for some reason it didn't like the submitted data and stopped the execution of the script.

Reset a form through javascript that is called via php

Ok I have googled for hours and found nothing that works. I need help desperately
I have got a form with the following elements in it.
<form action="sendmail.php" method="post" name="enquiry">
<table>
<tr>
<td>Name:-</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>Company:-</td>
<td> <input type="text" name="company" /></td>
</tr>
<tr>
<td>E-Mail:-</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Contact:-</td>
<td> <input type="text" name="contact" /></td>
</tr>
<tr>
<td>Requirement:-</td>
<td><textarea name="msg"></textarea></td>
</tr>
</table>
<input type="submit" value="submit" onclick="return validation(this.form);">
<input type="reset" value="Reset" />
</form>
and the php has a line like this:
<?php
if(mail($to, $subject,$message)) {
echo "<SCRIPT LANGUAGE='JavaScript'>alert('Your Enquiry was sent successfully we will get back to you shortly');
window.location.href='javascript:history.go(-1)';
document.enquiry.reset();
</SCRIPT>";
}
?>
Then there's an "else" with the same code but a different message.
The problem is when it redirects back to the form page it still has the data in the fields. What I prefer is a clean form with no data filled in when the user returns to the page.
Please note I am a newbie to javascript so try suggesting a fix that would be easy to comprehend.
Thanks a lot in advance!
That's because you're going back in the history - browsers remember forms when you go back/forward.
What you are doing isn't a "normal" user experience - I would suggest you print out a nice looking page saying thanks in the "sendmail.php" file and then let the user navigate to wherever they want to on your site.
as Ed said, you are going back in history, and the browser remembers it.
Try this:
instead of this line: window.location.href='javascript:history.go(-1)';
write : window.location.href='RelativePathToActualForm';
Your Problem is with the javascript code:
window.location.href='javascript:history.go(-1)';
document.enquiry.reset();
Remove this code
EDIT:
Use this code:
if(mail($to, $subject,$message)){?>
<SCRIPT LANGUAGE='JavaScript'>
alert('Your Enquiry was sent successfully we will get back to you shortly');
window.location.href='/*YOUR FORM PAGE LINK*/';
</SCRIPT>
<?php }
After processing the form post you should redirect to another page (or again to your form) and display your message there e.g.:
php header("Location: form.php?formpostwassuccessful=1");
then the form page
if(isset($_GET['formpostwassuccessful']))
echo "Thank you. Your form was sent.";
also see redirect after post?
First look at example of using php session-based flash messages http://mikeeverhart.net/php/session-based-flash-messages/
Usual flow:
User fills in the form
Presses submit
Your php script sendmail.php validates the form
If there were some validation errors [set error message]
If there were some mail sending errors [set error message]
If everything is ok [set success message]
Call from php redirect to the form display page.
[set error|success message] - using the link provided above how to set the message.
Now important part every time you render your form, you should check for set messages, if there are some messages - display them.
How do those messages work?
It simply sets the message to session ($_SESSION) array, and then when the message is displayed, the message is unset from session.
Simple solution : just use jquery - a single line is to be usee in the head section to include jquery in your page.
The javascript snippet you gave should contain:
window.location="theform_page_address" ;
instead of
window.location.href='javascript:history.go(-1)';
document.enquiry.reset();
and in the form page address: add the following js snippet in the head section :
<script type="text/javascript">
$(document).ready(function(){
$('input').val('');
$('select').val('-1');
$('textarea').val();
});
</script>
EDIT: I assume your form has input and textarea elements which have a blank default value, , and select elements that have -1 as the value for the default option.

Categories