PHP submit blank screen - script not running on POST? - php

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.

Related

(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

How to redirect page using $_SERVER['REQUEST_URI']

I'm building a page that has a form that's submitting to my database. The form needs to post to the current page to process, but since I'm using this same form on many pages, I would like a way to tell the form to use the user's current page to submit to. I know the code below can get this information, it's what I'm using to send url data to my database for another use.
$_SERVER['REQUEST_URI']
I'm just not sure how to use that within the code that loads the page. I suppose I could write something that will pull out the submitted url info that was just submitted to my database and then plug it in, but is there a way to just use the above code to do it? That seems easier, but when I tried plugging it in, it fails and just gives me a "404 not found" error, so I know I'm not doing it correctly.
It just needs to go in the simple form post action code below:
<form action="comment_box.php" method="post">
I've looked up similar questions, but I couldn't find anything that worked with what I needed, I just got more 404 errors. Any advice would be great, thanks!
If your posting to the same page the user is on you can do
<form action="" method="post">
Leaving the form action blank it will post to what ever the page the form is on.
Not sure what language your using but I assume php you then use
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
// form submit button was pressed your php code here
} else {
// no form submit button was press do nothing maybe show form html code here
}
?>
or what your trying to achieve
$url = $_SERVER['REQUEST_URI'];
Then in PHP
<form action="<?php echo $url; ?>/comment_box.php" method="post">
for example you have a following code
<input type="submit" name="click_me" value="Login">
then in the php, you have to check like
<?php
if(isset($_POST,$_POST['click_me']) && $_POST['click_me']="Login"){
//do your stuff
}
?>

form session data not posting, sessions working

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.

unset form submit button

<body>
<?php
if(isset($_POST['vendor_add_submit'])){
//INSERT INTO DB
unset( $_POST['vendor_add_submit'] );
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" >
<label>Email</label>
<input type="text" name="vendor_email" value="" />
<input type="submit" name="vendor_add_submit" value="SAVE" />
</form>
</body>
unset( $_POST['vendor_add_submit'] ); is used to prevent more than one time insertion into db on page refresh. I tested with print_r($_POST['vendor_add_submit'] ) before and after the unset and found that the unset() function does not work.
How can I achieve the purpose of the unset function, plz?
Unset isn't going to stop the refresh from being able to replay the POSTed data to the script. The unset function eliminated it for the remaining execution of that script, but a refresh is a fresh execution.
You could simply re-direct the browser to the entry pageafter doing your insert, that way a subsequent refresh will be safe.
//INSERT INTO DB
//...
header('Location: samepage.php');
exit();
I'm sure there are other ways to accomplish this as well.
Your approach cannot work, you would just be editing the data that the PHP script has recieved. If the user refreshes the browser then it will submit the same data again, and PHP will populate a fresh new $_POST with the data the browser sent.
If you want to stop a refresh resubmitting the data, then use the POST-REDIRECT-GET pattern.
The $_POST value will only be removed on the Server-Side Meaning that on that one request PHP will not be able to see or use it (You removed it).
But you are rendering the Submit button on the page's HTML so every time someone visits the page and submit the form they will submit the value again. And you will remove it again for PHP on that current request. So every request would insert the data into the database.
You might want to rather look into rather checking if the record already does exists (OR if the user has one already, not sure what you want) and then redirect them away from the page using header('Location: otherpage.php');.
Hope that helps...

Categories