HTML and PHP: how to manage a button in a form - php

I know that this can be a silly question, but I'm really going mad.
I'm new at PHP and I would like to create a form like this
where the user enters his name and a review of the restaurant, and when the button is clicked the data have to be added below the other reviews in the page. I tried this code in HTML to create the form
<form action="aggRecensione.php" method="post">
<p class="noIndent">Nome: <input type="text" name="nome"></p>
<p class="noIndent">Recensione</p>
<textarea name="recensione" rows="3" cols="40"></textarea>
<input type="submit" value="Aggiungi recensione" name="pulsanteRecensione" onclick="location.href='aggRecensione.php';">
</form>
and this code in PHP (aggRecensione.php)
<?php
$nome = $_POST('nome');
$testo = $_POST('recensione');
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
?>
but the PHP one doesn't work. I've never managed buttons before and all the tutorials I found didn't help me. What am I doing wrong?

Almost good, but maybe you can try
<?php
$nome = $_POST['nome'];
$testo = $_POST['recensione'];
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
?>
That because the content of $_POST is an array and array keys are indicated by the brackets []
Also remove the onclick="location.href='aggRecensione.php';"
And to be sure the user really hits the button you can also add this
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$nome = $_POST['nome'];
$testo = $_POST['recensione'];
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
}
?>
http://php.net/manual/en/reserved.variables.post.php

Remove this
onclick="location.href='aggRecensione.php';"
This will call the page as get method.
And change this two line.
$nome = $_POST['nome'];
$testo = $_POST['recensione'];

Related

How to get element by id in php?

I want to have an email sending system on my site.
The problem is when I try to assign a variable text from my HTML file it does not happen. I want that what is inside the variable should be written in the message of the email. Here's my code:
<html>
<?php include('form.php'); ?>
<head>
</head>
<body>
<form action="./form.php" method="post">
<div name="name"><input type="text" id="name"></div>
<div name="surname"><input type="text" id="surname"></div>
<div name="message"><textarea rows="4" cols="50" id="message">Inserisci qui il tuo testo.</textarea></div>
<div name="subject"><select id="subject">
<option selected="selected">--Inserisci Oggetto--</option>
<option>Registrazione al sito</option>
<option>Recupero credenziali</option>
</select></div>
<input type="submit" value="Invia penzolini"/>
<input type="hidden" name="button_pressed" value="1" />
</form>
</body>
</html>
<?php
$dochtml = new domDocument();
$dochtml->loadHTML('index.html');
if(isset($_POST['button_pressed']))
{
//prendi nome
$name = $dochtml->getElementById('name');
//prendi cognome
$surname = $dochtml->getElementById('surname');
//prendi l'oggetto della mail
$subject = $dochtml->getElementById('subject');
//msg<70 caratteri
$msg = "Inviato da" . ' ' . $name . $surname . ' ' . $dochtml->getElementById('message'); // /n=spazio
// manda mail
mail("panzersit#gmail.com",$subject,$msg);
echo 'Email inviata.';
}
?>
PHP cannot directly access your DOM. PHP runs only the server and on simple terms takes requests and gives a response.
Upon submit of this form to it's action page ./form.php, the values of the input forms are stored in the $_POST in a key named after it's name attribute. In your HTML code, add name attributes to the input tags like so:
<form action="./form.php" method="post">
<div name="name"><input type="text" name="name"></div>
<div name="surname"><input type="text" name="surname"></div>
</form>
Now if I submit this form and input Zachary for name input tag and Taylor for surname input tag, I can grab these values like so:
in ./form.php file:
$name = $_POST['name'];
// "Zachary"
$surname = $_POST['surname'];
// "Taylor"
To validate if anything was input in the first place, use:
isset($_POST['key']) since SOMETIMES input values with a null value are not even sent to the action page. This prevents PHP from throwing errors if you reference a $_POST key that does not exist.
Looking at documentation ( http://php.net/manual/pt_BR/domdocument.getelementbyid.php ) i'm locate a pontual observation:
"Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null."
Post the contents of form.php will help to recreate the scenario.
To get the posted data from your submitted form, you can do it using $_POST['fieldname']
Just try as below and see what you are getting after form submission.
//echo "<pre>";
//print_r($_POST);
Uncomment above 2 lines, see what you are getting and COMMENT IT AGAIN.
if( isset($_POST['name']) )
{
$name = $_POST['name'];
}
if( isset($_POST['surname']) )
{
$surname = $_POST['surname'];
}
if( isset($_POST['subject']) )
{
$subject = $_POST['subject'];
}

I cannot access variables from my form in php

I have been looking at this for a while now, and looking at all similar questions but I can't find anything that solves my problem.
So I'm working in main't html and php building a pretend shopping site on my own server. This is just for my own educational purposes, so basically it's just for fun.
This is only the third time I've done anything with html or php, so there is a lot I still don't understand and this project might have gotten a little bigger than I intended.
I have a page where the 'user' signs in from, and from there I used the session to bring the data they put in (username and such) to make a very simple greeting. That has worked mostly. The only problem there is if I refresh the new page too much sometimes it disappears.
Main problem is in the new page. I have a form for items in the store, where the user can choose an amount they want to buy. However when the submit button is pressed my check shows that the form is empty, and I don't understand why. I've messed with it a bunch, started from using $_POST to $_GET but that didn't help.
This is the start of my php which checks for things from the previous page.
<?php
//start session
session_start();
//check is post variables exist, if it does assign it
if (isset($_POST['username'])) {
$name = $_POST['username'];
$_SESSION['usersname'] = $name;
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
$_SESSION['useremail'] = $email;
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
$_SESSION['userpassword'] = $password;
}
$username = $_SESSION['usersname'];
$useremail = $_SESSION['useremail'];
$userpassword = $_SESSION['userpassword'];
Then the item list looks something like this.
<!--- List of all items and how many they want --->
<nav class="col-1">
<p> Shopping List </p>
<br/>
<form action="index.php" method="GET" name="items">
<table class="table1">
<tr><th>WEAPONS</th></tr>
<tr><td class="td1">
<br/>
<img class="disc" src="images/wand.png"></img><br/>
Item Name: Butterfly Wand<br/>
Price: $50.00<br/>
<input type="number" name="wandNum" min="0" style="width: 50px"/>
<br/>
<?php $wandprice = 50.00; ?>
</td></tr>
<tr><td class="td1">
<br/>
<img class="disc" src="images/sword.png"></img><br/>
Item Name: Normal Sword<br/>
Price: $20.00<br/>
<input type="number" name="swordNum" min="0" style="width: 50px"/>
<br/>
<?php $swordprice = 20.00; ?>
</td></tr>
<tr><td class="td1">
<br/>
<img class="disc" src="images/Bow_and_Arrows.png"></img><br/>
Item Name: Normal Bow<br/>
Price: $12.00<br/>
<input type="number" name="bowNum" min="0" style="width: 50px"/>
<br/>
<?php $bowprice = 12.00; ?>
</td></tr>
</table>
<input type="submit" id="orderButton" name="order" value="Order"/>
</form>
</nav>
Finally I wanted to put all the items and their information into an array somehow to store them. I'm not sure if this is the best way to achieve it either. I haven't gotten to this part because the form above keeps coming up empty. Even if I type in a value for every item.
if (isset($GET['items'])) {
$wandnum = $_GET['wandNum'];
$swordnum = $_GET['swordNum'];
$bownum = $_GET['bowNum'];
This just checks to see if the value is over 0...I think..then hopefully it will put the values in the array.
if ($wandnum > 0) {
$wand = array ("Butterfly Wand", $wandprice, $wandnum);
$items[] = array_push($wand);
}
if ($swordnum > 0) {
$sword = array ("Normal Sword", $swordprice, $swordnum);
$items[] = array_push($sword);
}
if ($bownum > 0) {
$bow = array ("Normal Bow", $bowprice, $bownum);
$items[] = array_push($bow);
}
}
?>
I can't get it past the if statement though because apparently it's not set. I don't have an IDE for html or php (any good free ones with debugging would be great) I ran the code through my command line and I ran fine. I just can't figure out why there are no values. My other page ran fine, so I'm not sure why this one is giving me trouble.
You need to add at the beginning:
<?php
if(isset($_GET['order'])) {
if (isset($_GET['items'])) {
$wandnum = $_GET['wandNum'];
$swordnum = $_GET['swordNum'];
$bownum = $_GET['bowNum'];
if ($wandnum > 0) {
$wand = array ("Butterfly Wand", $wandprice, $wandnum);
$items[] = array_push($wand);
}
if ($swordnum > 0) {
$sword = array ("Normal Sword", $swordprice, $swordnum);
$items[] = array_push($sword);
}
if ($bownum > 0) {
$bow = array ("Normal Bow", $bowprice, $bownum);
$items[] = array_push($bow);
}
}
}

How to make multiple AJAX queries after user input?

This seems like such a simple thing, but I have not been able to find adequate guidance on it for the life of me. I have only been able to find things about successive AJAX queries regardless of user input, like this or this.
What I'm trying to do is create a survey such that after a user answers a question, the website replaces the question with the next question, and so on.
Here's what I have so far (in a .php file):
In <head>, I have a function for each successive element to call:
<script type="text/javascript">
function nextPage(url) {
$("#consent-form").empty();
$("#consent-form").load(url);
}
</script>
Maybe that's just not how it's done. I have no idea. Like I said, I have not been able to find adequate help on this. As far as I can tell, empty() should not delete #consent-form, but only its content and children, which is exactly the behavior I want.
This is the initial html and php for the div I want to swap out after each answered question:
<div id="consent-form">
<?php
// Check for a valid email address.
$email = $emailErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "* Your email address is required.";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "* Please enter a valid email address.";
} else {
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$query = "INSERT INTO survey VALUES ('" . $email . "','" . $actual_link . "','','')";
mysql_query($query);
echo '<script type="text/javascript">'
, 'nextPage("survey.php");'
, '</script>'
;
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p>
[Consent form text]
</p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Please enter your email address: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error"> <?php echo $emailErr;?></span>
<br>
<input type="submit" value="Begin Study">
</form>
</div>
As I'm sure you can tell, I'm trying to do some form validation there.
This succcessfully injects the content of the next page ("survey.php") into the consent-form div. "survey.php" includes the following, using the nextPage() function shown above:
$("#csp_form").on('submit', function() {
nextPage("other.php");
});
But this fails to inject the consent-form div with "other.php".
Now, however, not even the form validation works. According to Firebug, the jquery library has raised some sort of error, even when I comment out all the jquery and javascript functions, and it's stuck in some perpetual loading operation. (This issue has been fixed.)
I am about to start throwing things. I have tried many different other techniques, but none of them worked and I have lost track of them. Hopefully this latest version will be sufficient to get guidance on this.
Sorry all that was so long, but usually people complain that there's too little information, so I wanted to make sure to include everything.
EDIT:
Per request, here's the current full content of survey.php (with the text content changed for privacy purposes):
<script type="text/javascript">
$("#icecream_form").on('submit', function() {
nextPage("other.php");
return false;
});
</script>
<br>
<h2>What's your favorite ice cream flavor?</h2>
<form method="post" id="icecream_form">
<input type="radio" name="icecream" value="vanilla"> Vanilla
<br>
<input type="radio" name="icecream" value="chocolate"> Chocolate
<br>
<input type="radio" name="icecream" value="other"> Something else
<br>
<input type="radio" name="icecream" value="none" checked> I don't have a favorite.
<br>
<br>
<input type="submit" name="icecream_submit" value="Go" onsubmit="return(false)">
</form>
After hitting submit, the content from consent-form comes back with an error message from the email form ("Please enter an email address"), implying that the email form was posted again. I cannot comprehend how that is possible if all the stuff from that div had truly been replaced by the stuff in survey.php.
I believe the issue was just that I was missing $(document).ready(function () { before $("#icecream_form").on('submit', function() {. This enabled return false; to actually work.
However, I also swapped out the PHP form validation with a jQuery version and deleted the nextPage() function in lieu of just having each page have their own .load(), so those things may also have made a difference.

POST Data is not sent

I'm having some weird issues with this code block, it's a little school project, going well so far but the form at the bottom is not returning any post data. the var_dump($_POST); never shows any post data being submitted from this particular form.
I just cannot understand why, been struggling with it for so long.
Here's the code, i couldn't understand to format it on this page, adding 4 indents for every line seemed a bit tedious.
<?php session_start();
require_once'user.class.php';
require_once 'posts.class.php';
require_once'comments.class.php';
$posts = new Posts($user->getID(), $db);
$comment = new Comments($user->getID(), $db);
include_once'includes/header.php';
include_once'includes/nav.php';
?>
<h2><br></h2>
<?php
include_once'includes/intro.php';
// CONTENT
$post = $posts->showPost($_GET['id']);
$title = $post['title'];
$content = $post['content'];
$created = $post['timestamp'];
echo "<section> <article class='blogPost'> <header> " . " <h2>$title</h2> " . "<p> Posted on $created <a href ='#comments'> X comments</a></p></header>" . "<p>$content</p>" . "</article> </section>";
var_dump($_POST);
if (isset($_POST['submit_comment']) && isset($_POST['id_comment'])) {
echo "Kom seg inn i ifen";
$pid = $_GET['id'];
$comment->newComment ($db, $user->getID(), $pid, $_POST['id_comment']);
header ("location: showPost.php?id=$pid");
exit ();
}
?>
<form name='commentform' action='showPost.php?id=<?php echo $_GET['id'];?>' method='POST'>
<h3>Post a comment</h3>
<p>
<label for='id_comment'>Comment</label>
<textarea name='id_comment' id='id_comment' required></textarea>
</p>
<p><input style='width: 100%;' type='submit' name='submit_comment' value='Legg til kommentar' /></p>
</form>
<?php
include_once'includes/asidefooter.php';
?>
Thanks for all help!
It looks like if post is data present, the user is redirected. You will only see the post data at the time the form is submitted, and the redirect will cause another page load and the data won't be present anymore.
Can you see the post data if you comment out the redirect, with:
//header ("location: showPost.php?id=$pid");
//exit ();
Something is causing a redirect, which is turning the request into a GET. If you're trying to submit to a index.php then don't forget the ending slash.

PHP: Using POST on a dynamic page redirects me to index.php and does not post the values

I am trying to get a guest book to work using PHP. I have managed to make it function, the thing is that I don't want the guest book to be in my index.php. I want it to be on a dynamic page, index.php?=guestbook for instance.
The problem is that when I put the code on another page rather than index.php the thing that happends when I fill out the fields and press the submit button, I get redirected to index.php and nothing is submited to my database. This all works fine as long as the code is in the index.php.
My first question is: What is causing this?
Second question: How do I get the code to function properly eventhough I have it in index.php?=guestbook?
Thanks in advance!
I am using xampp btw.
See below for the code:
<html>
<head>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>
<body>
<h1>Guestbook</h1><hr>
<?php
mysql_select_db ("guestbookdatabase") or die ("Couldn't find database!");
$queryget = mysql_query ("SELECT * FROM guestbook ORDER BY id ASC") or die("Error witch query.");
$querygetrownum = mysql_num_rows ($queryget);
if ($querygetrownum == 0)
echo "No posts have been made yet. Be the first!";
while ($row = mysql_fetch_assoc ($queryget))
{
$id = $row ['id'];
$name = $row ['name'];
$email = $row ['email'];
$message = $row ['message'];
$date = $row ['date'];
$time = $row ['time'];
if ($id%2)
$guestbookcomment = "guestbookcomment";
else
$guestbookcomment = "guestbookcommentdark";
echo "
<div class='$guestbookcomment'>
<div class='postheader'>
<b>Posted by $name ($email) on $date at $time</b>
</div>
<div class='message'>
".nl2br(strip_tags($message))."
</div>
</div>
";}
echo "<hr>";
if($_POST['submit'])
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$date = date("Y-m-d");
$time = date("H:i:s");
if ($name&&$email&&$message)
{
$querypost = mysql_query ("INSERT INTO guestbook VALUES ('','$name','$email','$message','$date','$time')");
echo "Please wait... <meta http-equiv='refresh' content='2'>";
}
else
echo "Please fill out all fields.";
}
echo "
<form action='index.php' method='POST'>
Your name: <input type='text' name='name' class='name' maxlength='25' ><br> <br>
Your email: <input type='text' name='email' class='email' maxlength='35'><br><br>
<div class='your_message'>
Your message:<input type='textarea' name='message' class='messagetextarea' maxlength='250'><br><br>
</div>
<input type='submit' name='submit' value='Post'>
</form>
";
?>
</body>
</html>
1) The action property of your form should be the same as the name of the file where the code is in. :) You create a guestbook.php, for example, but the action still is 'index.php'. Hence the problem. You send the POST data to index.php but there's no code to process it.
2) The query string doesn't affect the form. Only the filename.
I hope I understood your problem correctly.
Have you tried updating your form's action parameter to:
index.php?=guestbook
instead of just index.php?
If the problem resides on the server end than the victim to your problem is .htaccess (mod rewrite);
Otherwise, what do you really mean by this line of code?
echo "Please wait... <meta http-equiv='refresh' content='2'>";
< meta > refresh tag requires location to be mentioned where the redirect otherwise according to you refreshes the current page..
<meta http-equiv="refresh" content="2;url=http://stackoverflow.com/">
First, I'm assuming the file you're showing is index.php
Second, don't use index.php?=guestbook. URL parameters work within a key => value structure. In you're case you've only defined the value and no key.
Try using index.php?page=guestbook. this way, in your index.php file you can do something like:
if($_GET['page'] == 'guestbook') {
// ... your guestbook php code.
}
Then try setting your forms action attribute like this: action="index.php?page=guestbook".
Third, I'm going to assume that you have mysql connection code that isn't shown here. If not, take a look at mysql_connect().
Fourth, NEVER use unescaped data in a SQL query. You MUST escape your data to protect your database from being destroyed. Take a look at this wikipedia article which describes SQL Injection in greater detail: http://en.wikipedia.org/wiki/SQL_injection
Then take a look at mysql_real_escape_string() to learn how to prevent it with PHP and MySQL.
Fifth, don't use <meta http-equiv='refresh' content='2'> for redirect. Use PHP's header() function to redirect users, like this:
header('location: index.php');
exit(); // be sure to call exit() after you call header()
Also, just so you know, you CAN close PHP tags for large HTML blocks rather than using echo to print large static chunks of HTML:
<?php
// ... a bunch of PHP
?>
<form action="index.php" method="POST">
Your name: <input type="text" name="name" class="name" maxlength="25" ><br> <br>
Your email: <input type="text" name="email" class="email" maxlength="35"><br><br>
<div class="your_message">
Your message:<input type="textarea" name="message" class="messagetextarea" maxlength="250"><br><br>
</div>
<input type="submit" name="submit" value="Post">
</form>
<?php
// ... some more PHP
?>

Categories