Echo PHP variable to HTML after a form submit [duplicate] - php

This question already has answers here:
PHP Pass variable to next page
(9 answers)
Closed 3 years ago.
After a form submit, I am redirecting to the mentioned header location using below codes:
PHP Part:
$TestMessage = "This is a sample message. This is not a constant value. Original data will be collecting from DB";
if(mysqli_affected_rows($conn) > 0) {
header('Location:mydaomain/expenses?success=1');
}else{
header('Location:mydomain/expenses?failed=1');
}
HTML Part:
<div class="SubResult" id="SubResult" >
<?php
if ( isset($_GET['success']) && $_GET['success'] == 1 )
{
echo $TestMessage;
echo "<h1 style='color:green;padding:3%;'>Success !!</h1>";
}
if ( isset($_GET['failed']) && $_GET['failed'] == 1 )
{
echo $TestMessage;
echo "<h1 style='color:red;padding:3%;'>SQL Error !!</h1>";
}
?>
</div>
Issue with the above code is,HTML wont display $TestMessage PHP variable content.
Why I am using this header option in PHP:
Earlier, form was getting submitted whenever I refresh the page after an original submit. I found this solution to avoid that issue.
When I remove this header part from php file, I am able to echo variable to PHP (But at that I am facing issue with the form submission on page refresh issue)
Is there any way I can echo this variable to HTML ?

When you use header, you are doing a redirect, so your variable $TestMessage is not available after that, if you want to use it, make sure you pass using query string, for example:
header('Location:mydaomain/expenses?success=1&testMessage='.$TestMessage);
and in the next page use $_GET['testMessage'] to get his value.

Related

Five unique pages lead to one page. Can I change the <h1> according to the page they came from?

I have five unique forms each on a page of HTML. They then go to a PHP file to send the e-mail of data. Next they go to the HTML thank you page. I am hoping to change the heading according to which form they just submitted.
For example, if they submit a review, the should read "Thank you for your review" etc.
Technically all of these are saved as php files but only the e-mail page has php items.
Like <?php echo("<p>". $mail->getMessage()."</p>"); ?>
You should redirect to another php file and pass a parameter on url. Example:
sendemail.php
<?php
/** After send the email, check what kind form is (I don't know how do you check this).
This example is just to show you: */
if ($formType == 'review') {
$type = 'review';
} else if ($formType == 'anothertype') {
$type = 'anothertype';
}
header('Location: /thankspage.php?type=' . $type);
?>
thankspage.php
<?php
$type = $_GET['type'];
if ($type == 'review') {
echo '<h1>Thanks for your review</h1>';
} else if($type == 'anothertype') {
echo '<h1>Thanks for your anothertype</h1>';
}
?>
One way put a hidden field in your forms that'll get passed with the other form data. Then put an if statement on the thank you page and echo the appropriate message.
However, that'll only work either if you change the thank you page to php or change the page that receives and processes the form data to echo the thank you message as well

How to display alert box with timeout and then automatically redirect to another page using php [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
Hi i have to set a message box with time out when a specific data is already available in the database table.and then redirect to another page.My issue is that when page is getting redirected without showing the alert box.
Control statements php:
$count=0;
$sql="SELECT main_sec_name from main_sec_temp";
if($r=mysqli_query($con,$sql)) {
while($result= $r->fetch_row()) {
$count=$count+1;
}
}
if($count==0) {
if(mysqli_query($con,"INSERT INTO main_sec_temp(main_section_order,main_sec_name,main_number_of_ques,attempts) VALUES('','$sec_name','$no_question','$no_attempts')")) {
echo "Successfully Inserted";
header("location:index.php");
}else{
echo "Insertion Failed";
}
} else { //When Data is already exist
echo "<script>alert('already exist')</script>";
header("location:index.php");
}
You are trying to mix server side (PHP) and client side (Javascript) code in your example. Using header('Location:...') will get executed by PHP before the user will get a chance to see the contents of the page (also headers need to be used before any content is displayed on the page).
Additionaly, using javascript alert() requires user interaction by pressing the OK button, so you can't use timeout to redirect user.
Better approach would be something like this:
/// display html message and the javascript part of your code
echo "<h3 class='error'>Already exist</h3>";
echo "<script>";
echo "setTimeout(function(){ ";
echo " document.location='index.php';";
echo "}, 3000);"; // redirect after 3 seconds
echo "</script>";

trying to redirect a user to a different link after an input was insert [duplicate]

This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 years ago.
I am learning PHP and HTML (sorry for being noob) trying to redirect a customers to a different link after an input was insert. which means after he press verify he will be redirect to my website www.example.com/home.php This is my current code:
<div class="tclpad" style="width:90px;"> </div>
<div class="tclpad"><input class="bstd" value="Verify" type="submit"></div>
Also, when someone inserts a wrong information, i can see in the code:
<?php
if(isset($_SESSION['wrong'])) {
echo "<p class='error'>Authentication failed.</p>";
session_destroy();
}
?>
I want the user after he press verify will get a message 'Verified'.
Thank you so much guys for your help.
Check the accepted answer here: How to make a redirect in PHP?
I'm not sure exactly what you're looking for with the 'Verified' statement, but the answer above shows how to redirect the web page with the PHP header() function.
Edit:
I realized the header() function limits how the current page provides feedback. Instead, you could use javascript to redirect:
function redirectOnVerify(myVar) {
if(myVar === 'success'){
window.alert('You have verified successfully');
window.location = 'http://newlocation.com' ;
}
else if (myVar === 'failure') {
window.alert('Failed to verify');
}
else {
console.log('PHP auth error, neither success nor failure')
}
}
And then in your html:
<input onClick="redirectOnVerify('
<?php if(isset($_SESSION['right'])){
echo 'success'
}
else if (isset($_SESSION['wrong']){
echo 'failure'
}
else {}
?>
')">
/j
Use header() like
header("refersh: 2; url=page2url");
Refersh is a delay time here the page will redirect after 2 seconds if u don't want delay then either set refersh to 0 or do this
header("location=pag2url");

Constant Variables in PHP after page reloads

im very new to PHP, so please excuse me if this is a stupid question.
So here is the scenario.
Im writing a PHP all in one page that gets a random word from an array, scrambles the word, then lets the user guess the word.
now im using the isset(), so it declares the variable, then once submit is clicked, it will get in user input via _POST().
Now the problem
I need the calculated variable to remain constant, but once the page reloads, it regenerates the variable.
is there anyway i can get pass this?
<?php
function GetShuffWord()
{
$arrayName = array('word1','word2','word3','word4','word5');
$randWordIndex = rand(0,4);
$randomWord = $arrayName[$randWordIndex];
$shuffledWord = str_shuffle($randomWord);
return $shuffledWord;
}
if(!isset($_POST['Submit']))
{
define("shuffledWord", GetShuffWord());
$tempWord = shuffledWord;
// showing the user shuffled word
echo " <h1 style='font-size: 50px' align = 'center'> {$tempWord}
</h1>";
}
else
{
$tempWord = shuffledWord;
echo " <h1 style='font-size: 50px' align = 'center'>{$tempWord} </h1>";
echo "else part";
}
?>
another problem is that if i declare the variable in the if, i cannot use variable in the else with out re-generating it.
You can just include the value as a hidden input field in your form.
<input type="hidden" name="myCalculatedValue" value="<?= $tempWord ?>" />
Then when the form is submitted you can just get it via $_POST['myCalculatedValue']
You can use session and put a check that if session has it already dont overwrite.
And when u want to overwrite you can do so as well by passing another flag to the script in your post request.

Old PHP include code not working anymore, how to fix? [duplicate]

This question already has an answer here:
Enabling php.ini for backward compatibility
(1 answer)
Closed 9 years ago.
Ok so i want to have an include code on my index.php page that will include all of the other html pages within it. I used to do this using an id?=link.html link and this:
<?php
$id = $HTTP_GET_VARS['id'];
if ( !$id || $id == "" )
{
$number=10;
include("news/show_news.php");
}
else
{
include "$id";
}
?>
but apparantly http_get_vars is unrecognized or something? How can I fix this so that it will work? Or if things have changed, why should I not use this kind of thing for includes?
You can use $_GET to fetch the query string parameter by GET request, e.g.
index.php?id=123
The id value can be obtained by $_GET['id'].
p.s. your PHP codes are really old.
solved with the following:
<?php
if (!empty($_GET['id'])) {
$id = $_GET['id'];
$id = basename($id);
include("$id");
} else {
include("news/newsfilename.php");
}
?>
and
<a href="index.php?id=pagename.html">
Page Name
</a>
as the html

Categories