HTML Form Submit not readable for PHP - php

i´ve got a little problem with my php code.
The code contains a form that reloads the document. But after the reaload I cant read the POST data. Here is the HTML code:
<form action="config_page.php" method="post">
... some Inputs
<input type="submit" value="Save" name="config_btn" class="submitbtn_2">
</form>
On top of config_page.php ive got this PHP code:
if(isset($_POST["config_btn"])){
echo "isset";
//Some Database writing
}else{
echo "is not set";
}
Bizarrely, the output "is not set" always appears after submiting the form, but Database Changes are applied anyway... (Database Changes are only performed if the isset statement is true)
Can someone figure out the problem?
Thanks for your help!

POST values will always set after post or submit form with form post method
echo "is not set"; always true until you not click on submit or post any values. after submit click you will find $_POST["config_btn"] is set true so db queries runs.
so keep your form in else part.
So :-
if(isset($_POST["config_btn"])){
echo "isset";
//Some Database writing
}else{
echo "is not set";
}
When page loaded it's goes to else condition and will echo "is not set";
When you click on submit POST values found and it's runs your query.
if you redirect page again then again post values will be end and goes to else.

Related

php variable change without doing anything

Hello i have a strange problem i have the following form
echo "<td class='contact-delete'>
<form method='post' action='update_record.php'>";
echo "<button type='submit' value='" . $row['ID_PER'] . "' name='recordID' id = 'recordID'>edit</button>";
echo "</form>";
in the update_record.php I have the following code
$id2update = $_POST['recordID'];
echo $id2update ;
session_start();
if(!$_SESSION['logged']){
header("refresh:3; url=start_page.php" );}
// above this part of code there is an other form with a submit button
else if(isset($_POST['submit'])){
echo $id2update ;
}
The problem is that the first echo outputs the variable as it supposed but the second echo does not output anything it is null. Can anyone give me an explanation?
edit:
The 2nd echo is being called but the value is null!
You say "above this part of code there is an other form with a submit button". I assume it is that you are trying to echo with the second submit? In that case the data is never submitted. When you submit an HTML form only that form is submitted. Any inputs/buttons/etc in other forms on the page are not sent to the server and so not available in the PHP code. This is by design.
Thus your code as it stands should never reach the second echo.
(Technically only non-disabled form elements with non-null name in the current form are submitted)
Edit:
I think I now understand the comment in your code. You have one form in another file which submits to update_record.php In that request you render a new form (as part of update_record.php) with a submit button. That new form submits to itself with the submit button. If this is correct then the point is that the submit of the form from update_record.php (the one with the submit button) is a new request. You set the value of $id2update in one request but then do a new request and in that it is not set. You should include that value as a hidden input in the form rendered in update_record.php:
<input type="hidden" name="recordID" value="<?php echo $id2update;?>" />
then, when the second request is made (when the update_record.php form is submitted) the vlaue will be fetched again.
Each request must be treated for itself - the server does not automatically know which requests go together (up to data saved in the session of course).

How do i go about echoing back to a form from a form post action?

I have a form containing a textarea for inputing text into. The form also contains a submit button. After pressing the submit button it posts the text within the textarea into my php document. Within my php document the text is added to a database. Once it has been added to the database I would like it to echo back a response telling the user that it has added the text to the database successfully.
However, if i make it echo that response back to the home page, there is nowhere declared for it to display the echoed message. Has anyone got an idea of what i should be doing in order to get this working? Many Thanks.
Normally i wouldn't use a post straight from the form and i would use ajax and then display the data within a paragraph or something on it's return, however since the form is doing the post it's self i am not sure where to then declare where the response should show up.
The bellow displays my html form code and shows it's action to post to a php file.
<div id="userban2"><form id="bannable" action="/onlineusers.php" method="post"><p> Type username to ban bellow:</p>
<textarea name="banned" id="banned" maxlength="255"></textarea><br/>
<input type="submit" value="Send" class="extrabuttons" onclick="return false; preventDefault();">
<div id="cancelban" class="extrabuttons"><p> cancel</p></div>
</form>
However when in my php file i write ....
echo "the information has been added to the database successfully";
It might send the echo back however it isn't declared to display anywhere how can i change this to make it display the response within my form?
As requested return from my php
if(isset($_POST["banned"])){
$ban_name = $_POST["banned"];
bannedd($ban_name);
}
function bannedd($ban_name) {
$query1 = mysql_query("INSERT INTO banned_users (username,firstname,lastname,email,password,ip_address,sign_up_date,last_logged_in,about,sta rr,userpref) VALUES('$usernameb','$fnameb','$lnameb','$emailb','$passwordb','$ip_addressb','$sign_up_date b','$last_logged_inb','$aboutb','$starrb','$userprefb')") or die("Could not insert your informaion");
echo "This user has successfully been banned";
}
The form posts what is written in the form due to it having the action and method of post to my php. However should i then have any return i am not sure how i declare where the returned information should then show (The echoed message).
If I understand you correctly, your form is in some index.php file and sends the data to other file - onlineusers.php, and you want to display the message in the original page?
If this is the case, the most simple way I can think of is redirect back to the original page with a URL parameter, instead of echoing.
Do this at the end of onlineusers.php:
<?php
// insert text into DB ...
header("Location: index.php?result=ok");
?>
This redirects the browser back to the original page with the form. There you check if the status variable is set:
<html>
<head></head>
<body>
<?php if(isset($_GET["result"]) && $_GET["result"]=="ok") { ?>
<p>The information has been added to the database successfully</p>
<?php } ?>
<form> ... </form>
</body>
</html>
As you can probably see, you could set other results, such as "error" this way.
If you don't like the extra string in your URL, then create a cookie after processing the form in onlineusers.php and back at the original page, check if such cookie has been set. If you need more detail on that, let me know. And if you're asking something completely different, well, never mind :)
Your form is being submitted to /onlineusers.php
This is where you would want to add your echo statement.
If you require the info on the same page you technically return to the same page with the form action being $_SERVER['PHP_SELF'].
<form id="bannable" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Then you can put in a conditional statement prior to the load of your document, and include the PHP script.
<?php
$testVar = false;
$msg = '';
if($_POST) {
include '/onlineusers.php';
//... do something e.g post to database and return true.
}
if($testVar) {
$msg = 'Successful writing to DB!';
} ?>
<html>
<body>
<?php echo $msg; ?>
</body>
</html>
This will check to see if you have any post data, if you do, then it includes the script you specify. Maybe set $testVar to true if the writing to DB is successful, and then return $msg in your HTML.

Update page after successful insertion into MySQL table

I am making a page that has a bunch of fields that allows the user to enter in information and submit it to a database. This page is called 'add.php' I created a 'form' tag and had the information posted to another page called 'process.php' where the information is collected, then inserted into the database. I want the user to know whether it was successful or not, so I was wondering how to tell the user something specific on the 'add.php' page. like "insertion successful!" at the top of the page.
I thought of including the 'process.php' code in 'add.php', then calling the 'add.php' in the action of the form, but the code gets called the first time the page is loaded, which inserts a completely blank entry into the database.
Should I implement some sort of flag that is only set to true after the 'submit' button is clicked? Or is there another way to update the page and tell the user the status of the insertion?
I can paste the relevant code as needed. :)
Thanks!
Assuming that you are using the post method in your form and php, you can simply check if a post was made:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// form was posted, process and display output
}
else
{
// nothing was posted, normal get request, show form
}
just check if query worked well. If no exception was thrown, it mostly has, and the add appropriate message with output.
First you need to check and handle errors
try
{
}
catch(Exception $e){
header('Location:oldlocation.php?succ=0')
exit();
}
header('Location:oldlocation.php?succ=0')
exit();
If all goes well, you can also redirect to a new location(as shown in code). This has to be done properly, you may redirect back to the old location, with additional data like
oldlocation.php?succ=1;
If anything goes wrong redirect to
oldlocation.php?succ=0
Then fetch the succ using $_GET["succ"] and print appropriate message.
If you din get, comment.
Here's what I would do...
Keep your processing data in one file, and include the form file at the end
//add.php
//if the form is submitted make the database entry
if(isset($_POST['foo']) AND $_POST['foo'] != '')
{
//code to process form submission
$success = 'success!';
}
//include the form
include addform.php
in addform.php put your form. Include an 'isset' that is watching for $success to alert that the entry was successful
//addform.php
<?php if(isset($success)){ echo "<h2> Data successfully entered! </h2>";} ?>
<form action='' method='POST'>
<input type='text' name='foo' />
//etc
</form>
So once you submit the form, the code starts at the top of add.php - the 'isset' sees the $_POST submission, runs the form submission code and sets the success variable. Then, it includes the form page. The form page has an 'isset' that is watching for the success variable. When you first navigate to the page, or if you refresh, the add.php code will skip the first code block (the form submission stuff) and won't make a database submission or set the success variable.

Form submit dialog

I have a basic form that asks for certain information and then validates the form using javascript before actually submitting it to a seperate php file to email the form submission to me however, after successfully submitting the form, it goes to blank page and then a Thank you popup shows up. How do I set it so hitting the submit button doesn't go to a new page but just displays the popup on the current page?
My code for filling out the form is:
<form action="send_group.php" method="post" onsubmit='return formValidator()'>
//Asks to input information
<input type="submit" value="Submit" />
</form>
My PHP code is:
<?php
$webmaster_email = "email#email.com"; //E-mail the message will be sent to
$info = $_REQUEST['info'] ;
$info1= $_REQUEST['info1'] ;
$info2= $_REQUEST['info2'] ;
$info3= $_REQUEST['info4'] ;
mail( "$webmaster_email", "Information Form Submission",
"Info: $info
Info1: $info1
Info2: $info2
Info3: $info3" );
echo "<script type='text/javascript'>\n";
echo "alert('Thank you for your booking request. We will get back to you as soon as possible.');\n";
echo "</script>";
?>
You have to use an AJAX request.
So you bind an onclick event on your submit button, then you send an AJAX request, and when the AJAX request suceeded you display your response (Bad or not).
JQuery is really powerful and easy for AJAX request, look here : http://api.jquery.com/jQuery.ajax/
You can either use AJAX to submit the data in the background, or, the easier option put the from and php into the same php file.
Well, the browser shows exactly what it receives from your php-script.
One way to solve your problem without Ajax could be the following approach: To display your original page after the request has been processed add e.g.
header("location: your_form_page.php?req=1");
in case of success, and e.g.
header("location: your_form_page.php?req=-1");
in case an error occurred to send_group.php. The GET parameter req can be used to display either the thank-you-box or an error message. The switching logic must of course be implemented already in your_form_page.php, e.g.
if ($_GET['req'] == '1') {
echo "<script type='text/javascript'>\n";
echo "alert('Thank you for ...');\n";
echo "</script>";
} else if ($_GET['req'] == '-1') {
echo "<script type='text/javascript'>\n";
echo "alert('Error ...');\n";
echo "</script>";
}
You have to redirect the user after the script successfully finishes, using the location header
header("location: formPage.php?success=1");
Then on your original form page you can run the javascript.
Use xhrRequest (ajax) for retrieve information from validation page and then show result to your user.

returning from a form submit call to a .php file

I have a questionnaire in a form. In the end of it the submit button is pressed that is supposed to call a .php file that inserts data into a database through its action information and afterwards show the last page that contains something like "thank you for participating etc." via the onsubmit info.
problem is that the last page is shown before the .php file is shown which means it is visible only for like half a second and then the php script is carried out which ends up showing a blank page.
The php script works it inserts data into the questionnaire correctly so there should be no mistakes syntax-wise.
any ideas if I have to exit the cript or something and return to the .html file or what could be wrong?
on your opening form tag add action="submit.php"
then once it goes to that page when the submit button is hit add this to the bottom of that php page:
header("Location: successfull.html");
IT sounds like what youre doing is showing the message with Javascript via the onsubmit event - this happens before the request is even set to the server and the php script. Youd either need to do an ajax form submission and then display the message when the request completes or make the php script redirect to the success message page when it is done.
But this is all just speculation without seeing any code... you should post some :-)
Why not submit the form to process.php then process it:
if(isset($_POST)){
$name = $_POST['name'];
// etc etc
// if all error checks pass, then echo out - thanks for taking part in our survey!
}
What you're doing is submitting it, and it seems you're getting javascript to say 'thank you' but it is being submitted before this thank you message can be displayed - no harm in echoing this out on your .php page!!
Update
You mention about redirecting to a page afterwards, but this can be done by:
header("Location: where/to/go.php");
exit;
But you can't do this with the above (echoing out a success) since it will redirect straight away.
The way I deal with this is putting the html contents into the php file.
<?php
if (!isset($_POST["submit"])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>survey</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
...... (your form) ......
<input type="submit" value="submit" name="submit"><br />
</form><br />
</body>
</html>
<?
}
else {
$db = new PDO('...');
$db->exec(...);
echo "Thank you!";
}
?>
A few ways you could accomplish that.
You could make the php file it submits send out the data for the "thank you for participating" page (if you're fine with simply going to another page).
Alternatively, if you want to stay on the same page but just show the "thank you" notification, I would use JavaScript to disable the default action (e.preventDefault(); in the event handler) for the "submit" button on the forum, then also use JavaScript to use AJAX to submit the data.
An example (using JQuery), which won't change your page and perform the submit in the background, and display the "thank you" when done, on the current page.
$("a#confirmSubmit").click(function(e) {
e.preventDefault(); // Prevents the submit button from changing pages
data = {
Name: $("input#Name").attr("value")
// Add other data here also
};
$.post("/page/to/submit/to.php", data, function(d) {
//Write the code here to show the "thank you" notification.
//It will show upon completion here.
});
});
If you want to check for errors with inserting into the DB, you could check the value of the data of the AJAX call, to conditionally show the error. You can then return the user to the exact same form they were already on, with all the data still there, and show them an error message.

Categories